feat: argon2id passwords, session cookies, bot bearer tokens
Adds the full auth flow. Reads stay public; writes (currently only POST
/api/v1/mangas) require a CurrentUser. Both browsers and bot scripts hit
the same endpoints — they just present credentials differently.
Migration 0002_auth.sql introduces users.password_hash, a sessions
table, and an api_tokens table. Sessions and api_tokens store only
sha256(raw_token) — the raw value lives in the cookie or the
Authorization header.
New endpoints under /api/v1/auth/:
- POST /register — argon2id hash, creates a session, sets cookie.
- POST /login — verifies, rotates to a fresh session (old ones expire
naturally so other devices stay signed in).
- POST /logout — deletes the server-side session row + clears the
cookie via Max-Age=0.
- GET /me — current user via the new CurrentUser extractor.
- POST /tokens — issue a bot bearer token; raw value returned exactly
once at creation.
- DELETE /tokens/{id} — owner-only: 404 if unknown, 403 if it exists
but belongs to another user, 204 on success.
The CurrentUser axum extractor resolves cookie first, then
Authorization: Bearer; failure → AppError::Unauthenticated (401). New
AppError variants Unauthenticated/Forbidden/Conflict carry the matching
envelope codes; the top-level match in `code()` stays exhaustive.
Backend integration coverage in tests/api_auth.rs: register sets a
HttpOnly SameSite=Lax cookie and never leaks password_hash; duplicate
username → 409; weak password → 400; login rotates the cookie; wrong
password / unknown user → 401; /me with vs without cookie; logout
invalidates the cookie; bot-token roundtrip via Bearer; user A cannot
delete user B's token (403); unknown delete → 404.
Frontend:
- lib/api/auth.ts — typed wrappers; me() returns null on 401.
- lib/session.svelte.ts — per-tab user state with a seq counter to
guard against an in-flight /me clobbering a fresh setUser.
- lib/api/client.ts — request<T> returns undefined for 204.
- routes/login + routes/register — forms with action="javascript:void(0)"
so the no-JS path is a no-op (avoids the hydration-race where a
pre-attach click would submit via the browser default).
- routes/+layout.svelte — session-aware nav: spinner → user + Logout,
or Login / Register.
- e2e/auth-flow.spec.ts — login flips the layout, logout flips back;
bad credentials surface the API error message.
Config grows AuthConfig (cookie_secure, cookie_domain, session_ttl_days)
and CORS_ALLOWED_ORIGINS. CORS middleware is mounted in app::build and
stays a no-op (same-origin) until origins are listed.
Lockstep version bump to 0.3.0.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
179
backend/Cargo.lock
generated
179
backend/Cargo.lock
generated
@@ -32,6 +32,18 @@ version = "1.0.102"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
|
||||
|
||||
[[package]]
|
||||
name = "argon2"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3c3610892ee6e0cbce8ae2700349fcf8f98adb0dbfbee85aec3c9179d29cc072"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"blake2",
|
||||
"cpufeatures",
|
||||
"password-hash",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-trait"
|
||||
version = "0.1.89"
|
||||
@@ -120,6 +132,31 @@ dependencies = [
|
||||
"tracing",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "axum-extra"
|
||||
version = "0.9.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c794b30c904f0a1c2fb7740f7df7f7972dfaa14ef6f57cb6178dc63e5dca2f04"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"axum-core",
|
||||
"bytes",
|
||||
"cookie",
|
||||
"fastrand",
|
||||
"futures-util",
|
||||
"headers",
|
||||
"http",
|
||||
"http-body",
|
||||
"http-body-util",
|
||||
"mime",
|
||||
"multer",
|
||||
"pin-project-lite",
|
||||
"serde",
|
||||
"tower",
|
||||
"tower-layer",
|
||||
"tower-service",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "axum-macros"
|
||||
version = "0.4.2"
|
||||
@@ -152,6 +189,15 @@ dependencies = [
|
||||
"serde_core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "blake2"
|
||||
version = "0.10.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"
|
||||
dependencies = [
|
||||
"digest",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "block-buffer"
|
||||
version = "0.10.4"
|
||||
@@ -224,6 +270,17 @@ version = "0.9.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8"
|
||||
|
||||
[[package]]
|
||||
name = "cookie"
|
||||
version = "0.18.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747"
|
||||
dependencies = [
|
||||
"percent-encoding",
|
||||
"time",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "core-foundation-sys"
|
||||
version = "0.8.7"
|
||||
@@ -290,6 +347,15 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "deranged"
|
||||
version = "0.5.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
|
||||
dependencies = [
|
||||
"powerfmt",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
@@ -328,6 +394,15 @@ dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "encoding_rs"
|
||||
version = "0.8.35"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "equivalent"
|
||||
version = "1.0.2"
|
||||
@@ -535,6 +610,30 @@ dependencies = [
|
||||
"hashbrown 0.15.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "headers"
|
||||
version = "0.4.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b3314d5adb5d94bcdf56771f2e50dbbc80bb4bdf88967526706205ac9eff24eb"
|
||||
dependencies = [
|
||||
"base64",
|
||||
"bytes",
|
||||
"headers-core",
|
||||
"http",
|
||||
"httpdate",
|
||||
"mime",
|
||||
"sha1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "headers-core"
|
||||
version = "0.3.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "54b4a22553d4242c49fddb9ba998a99962b5cc6f22cb5a3482bec22522403ce4"
|
||||
dependencies = [
|
||||
"http",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "heck"
|
||||
version = "0.5.0"
|
||||
@@ -895,20 +994,27 @@ checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
|
||||
|
||||
[[package]]
|
||||
name = "mangalord"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"argon2",
|
||||
"async-trait",
|
||||
"axum",
|
||||
"axum-extra",
|
||||
"base64",
|
||||
"chrono",
|
||||
"dotenvy",
|
||||
"http-body-util",
|
||||
"mime",
|
||||
"rand",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha2",
|
||||
"sqlx",
|
||||
"subtle",
|
||||
"tempfile",
|
||||
"thiserror 1.0.69",
|
||||
"time",
|
||||
"tokio",
|
||||
"tower",
|
||||
"tower-http",
|
||||
@@ -965,6 +1071,23 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "multer"
|
||||
version = "3.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"encoding_rs",
|
||||
"futures-util",
|
||||
"http",
|
||||
"httparse",
|
||||
"memchr",
|
||||
"mime",
|
||||
"spin",
|
||||
"version_check",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nu-ansi-term"
|
||||
version = "0.50.3"
|
||||
@@ -990,6 +1113,12 @@ dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-conv"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c6673768db2d862beb9b39a78fdcb1a69439615d5794a1be50caa9bc92c81967"
|
||||
|
||||
[[package]]
|
||||
name = "num-integer"
|
||||
version = "0.1.46"
|
||||
@@ -1055,6 +1184,17 @@ dependencies = [
|
||||
"windows-link",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "password-hash"
|
||||
version = "0.5.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166"
|
||||
dependencies = [
|
||||
"base64ct",
|
||||
"rand_core",
|
||||
"subtle",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pem-rfc7468"
|
||||
version = "0.7.0"
|
||||
@@ -1118,6 +1258,12 @@ dependencies = [
|
||||
"zerovec",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "powerfmt"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
|
||||
|
||||
[[package]]
|
||||
name = "ppv-lite86"
|
||||
version = "0.2.21"
|
||||
@@ -1759,6 +1905,37 @@ dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time"
|
||||
version = "0.3.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c"
|
||||
dependencies = [
|
||||
"deranged",
|
||||
"itoa",
|
||||
"num-conv",
|
||||
"powerfmt",
|
||||
"serde_core",
|
||||
"time-core",
|
||||
"time-macros",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time-core"
|
||||
version = "0.1.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca"
|
||||
|
||||
[[package]]
|
||||
name = "time-macros"
|
||||
version = "0.2.27"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215"
|
||||
dependencies = [
|
||||
"num-conv",
|
||||
"time-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tinystr"
|
||||
version = "0.8.3"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "mangalord"
|
||||
version = "0.2.0"
|
||||
version = "0.3.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
@@ -26,6 +26,13 @@ thiserror = "1"
|
||||
anyhow = "1"
|
||||
async-trait = "0.1"
|
||||
dotenvy = "0.15"
|
||||
argon2 = "0.5"
|
||||
rand = "0.8"
|
||||
sha2 = "0.10"
|
||||
subtle = "2"
|
||||
base64 = "0.22"
|
||||
axum-extra = { version = "0.9", features = ["cookie", "typed-header"] }
|
||||
time = "0.3"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
|
||||
30
backend/migrations/0002_auth.sql
Normal file
30
backend/migrations/0002_auth.sql
Normal file
@@ -0,0 +1,30 @@
|
||||
-- Auth: passwords on users, server-side sessions, and bot API tokens.
|
||||
--
|
||||
-- Sessions and api_tokens both store sha256(raw_token) as bytea. The raw
|
||||
-- token is held by the client (cookie for sessions, Authorization bearer
|
||||
-- header for tokens); the server only ever sees the hash at rest, so a
|
||||
-- read of the DB does not yield reusable credentials.
|
||||
|
||||
ALTER TABLE users ADD COLUMN password_hash text NOT NULL;
|
||||
|
||||
CREATE TABLE sessions (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
token_hash bytea NOT NULL UNIQUE,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
expires_at timestamptz NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX sessions_user_idx ON sessions (user_id);
|
||||
CREATE INDEX sessions_expires_idx ON sessions (expires_at);
|
||||
|
||||
CREATE TABLE api_tokens (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
name text NOT NULL,
|
||||
token_hash bytea NOT NULL UNIQUE,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
last_used_at timestamptz
|
||||
);
|
||||
|
||||
CREATE INDEX api_tokens_user_idx ON api_tokens (user_id, created_at DESC);
|
||||
207
backend/src/api/auth.rs
Normal file
207
backend/src/api/auth.rs
Normal file
@@ -0,0 +1,207 @@
|
||||
//! Authentication endpoints — register, login, logout, current-user, and
|
||||
//! bot API token management. Session cookies are HttpOnly + SameSite=Lax
|
||||
//! and rotate on login (a fresh session row is created; old sessions
|
||||
//! expire naturally rather than being explicitly invalidated, so other
|
||||
//! devices keep their existing logins).
|
||||
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::IntoResponse;
|
||||
use axum::routing::{delete, get, post};
|
||||
use axum::{Json, Router};
|
||||
use axum_extra::extract::cookie::{Cookie, CookieJar, SameSite};
|
||||
use chrono::{Duration, Utc};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::app::AppState;
|
||||
use crate::auth::extractor::{CurrentUser, SESSION_COOKIE_NAME};
|
||||
use crate::auth::password::{hash_password, verify_password};
|
||||
use crate::auth::token::{generate_token, hash_token};
|
||||
use crate::config::AuthConfig;
|
||||
use crate::domain::{ApiToken, User};
|
||||
use crate::error::{AppError, AppResult};
|
||||
use crate::repo;
|
||||
|
||||
pub fn routes() -> Router<AppState> {
|
||||
Router::new()
|
||||
.route("/auth/register", post(register))
|
||||
.route("/auth/login", post(login))
|
||||
.route("/auth/logout", post(logout))
|
||||
.route("/auth/me", get(me))
|
||||
.route("/auth/tokens", post(create_token))
|
||||
.route("/auth/tokens/:id", delete(delete_token))
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct Credentials {
|
||||
pub username: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct AuthResponse {
|
||||
pub user: User,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct CreateTokenInput {
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub struct CreatedTokenResponse {
|
||||
#[serde(flatten)]
|
||||
pub token: ApiToken,
|
||||
/// Raw bearer token — returned exactly once at creation.
|
||||
pub bearer: String,
|
||||
}
|
||||
|
||||
async fn register(
|
||||
State(state): State<AppState>,
|
||||
jar: CookieJar,
|
||||
Json(input): Json<Credentials>,
|
||||
) -> AppResult<impl IntoResponse> {
|
||||
let username = input.username.trim();
|
||||
validate_username(username)?;
|
||||
validate_password(&input.password)?;
|
||||
|
||||
let pwhash = hash_password(&input.password)?;
|
||||
let user = repo::user::create(&state.db, username, &pwhash).await?;
|
||||
let jar = start_session(&state, &user, jar).await?;
|
||||
Ok((StatusCode::CREATED, jar, Json(AuthResponse { user })))
|
||||
}
|
||||
|
||||
async fn login(
|
||||
State(state): State<AppState>,
|
||||
jar: CookieJar,
|
||||
Json(input): Json<Credentials>,
|
||||
) -> AppResult<impl IntoResponse> {
|
||||
let username = input.username.trim();
|
||||
if username.is_empty() || input.password.is_empty() {
|
||||
return Err(AppError::InvalidInput(
|
||||
"username and password are required".into(),
|
||||
));
|
||||
}
|
||||
|
||||
let user = repo::user::find_by_username(&state.db, username)
|
||||
.await?
|
||||
.ok_or(AppError::Unauthenticated)?;
|
||||
if !verify_password(&input.password, &user.password_hash) {
|
||||
return Err(AppError::Unauthenticated);
|
||||
}
|
||||
|
||||
let jar = start_session(&state, &user, jar).await?;
|
||||
Ok((StatusCode::OK, jar, Json(AuthResponse { user })))
|
||||
}
|
||||
|
||||
async fn logout(
|
||||
State(state): State<AppState>,
|
||||
jar: CookieJar,
|
||||
) -> AppResult<impl IntoResponse> {
|
||||
if let Some(cookie) = jar.get(SESSION_COOKIE_NAME) {
|
||||
let hash = hash_token(cookie.value());
|
||||
repo::session::delete_by_token_hash(&state.db, &hash).await?;
|
||||
}
|
||||
let jar = jar.add(build_expired_cookie(&state.auth));
|
||||
Ok((StatusCode::NO_CONTENT, jar))
|
||||
}
|
||||
|
||||
async fn me(CurrentUser(user): CurrentUser) -> AppResult<Json<AuthResponse>> {
|
||||
Ok(Json(AuthResponse { user }))
|
||||
}
|
||||
|
||||
async fn create_token(
|
||||
State(state): State<AppState>,
|
||||
CurrentUser(user): CurrentUser,
|
||||
Json(input): Json<CreateTokenInput>,
|
||||
) -> AppResult<impl IntoResponse> {
|
||||
let name = input.name.trim();
|
||||
if name.is_empty() {
|
||||
return Err(AppError::InvalidInput("token name is required".into()));
|
||||
}
|
||||
let (raw, hash) = generate_token();
|
||||
let token = repo::api_token::create(&state.db, user.id, name, &hash).await?;
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
Json(CreatedTokenResponse { token, bearer: raw }),
|
||||
))
|
||||
}
|
||||
|
||||
async fn delete_token(
|
||||
State(state): State<AppState>,
|
||||
CurrentUser(user): CurrentUser,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> AppResult<StatusCode> {
|
||||
match repo::api_token::find_owner(&state.db, id).await? {
|
||||
None => Err(AppError::NotFound),
|
||||
Some(owner) if owner != user.id => Err(AppError::Forbidden),
|
||||
Some(_) => {
|
||||
repo::api_token::delete(&state.db, id).await?;
|
||||
Ok(StatusCode::NO_CONTENT)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn start_session(
|
||||
state: &AppState,
|
||||
user: &User,
|
||||
jar: CookieJar,
|
||||
) -> AppResult<CookieJar> {
|
||||
let (raw, hash) = generate_token();
|
||||
let expires_at = Utc::now() + Duration::days(state.auth.session_ttl_days);
|
||||
repo::session::create(&state.db, user.id, &hash, expires_at).await?;
|
||||
Ok(jar.add(build_session_cookie(raw, &state.auth)))
|
||||
}
|
||||
|
||||
fn build_session_cookie(raw: String, cfg: &AuthConfig) -> Cookie<'static> {
|
||||
let mut builder = Cookie::build((SESSION_COOKIE_NAME, raw))
|
||||
.http_only(true)
|
||||
.secure(cfg.cookie_secure)
|
||||
.same_site(SameSite::Lax)
|
||||
.path("/")
|
||||
.max_age(time::Duration::days(cfg.session_ttl_days));
|
||||
if let Some(domain) = &cfg.cookie_domain {
|
||||
builder = builder.domain(domain.clone());
|
||||
}
|
||||
builder.build()
|
||||
}
|
||||
|
||||
fn build_expired_cookie(cfg: &AuthConfig) -> Cookie<'static> {
|
||||
let mut builder = Cookie::build((SESSION_COOKIE_NAME, ""))
|
||||
.http_only(true)
|
||||
.secure(cfg.cookie_secure)
|
||||
.same_site(SameSite::Lax)
|
||||
.path("/")
|
||||
.max_age(time::Duration::seconds(0));
|
||||
if let Some(domain) = &cfg.cookie_domain {
|
||||
builder = builder.domain(domain.clone());
|
||||
}
|
||||
builder.build()
|
||||
}
|
||||
|
||||
fn validate_username(u: &str) -> AppResult<()> {
|
||||
if u.is_empty() {
|
||||
return Err(AppError::InvalidInput("username is required".into()));
|
||||
}
|
||||
if u.len() < 3 || u.len() > 32 {
|
||||
return Err(AppError::InvalidInput(
|
||||
"username must be 3-32 characters".into(),
|
||||
));
|
||||
}
|
||||
if !u.chars().all(|c| c.is_alphanumeric() || c == '_' || c == '-') {
|
||||
return Err(AppError::InvalidInput(
|
||||
"username may only contain letters, digits, _ and -".into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_password(p: &str) -> AppResult<()> {
|
||||
if p.len() < 8 {
|
||||
return Err(AppError::InvalidInput(
|
||||
"password must be at least 8 characters".into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use uuid::Uuid;
|
||||
|
||||
use crate::api::pagination::PagedResponse;
|
||||
use crate::app::AppState;
|
||||
use crate::auth::extractor::CurrentUser;
|
||||
use crate::domain::manga::{Manga, NewManga};
|
||||
use crate::error::{AppError, AppResult};
|
||||
use crate::repo;
|
||||
@@ -54,6 +55,7 @@ async fn get_one(
|
||||
|
||||
async fn create(
|
||||
State(state): State<AppState>,
|
||||
CurrentUser(_user): CurrentUser,
|
||||
Json(input): Json<NewManga>,
|
||||
) -> AppResult<Json<Manga>> {
|
||||
if input.title.trim().is_empty() {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
pub mod auth;
|
||||
pub mod files;
|
||||
pub mod health;
|
||||
pub mod mangas;
|
||||
@@ -12,4 +13,5 @@ pub fn routes() -> Router<AppState> {
|
||||
.merge(health::routes())
|
||||
.merge(mangas::routes())
|
||||
.merge(files::routes())
|
||||
.merge(auth::routes())
|
||||
}
|
||||
|
||||
@@ -1,17 +1,20 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::http::{HeaderName, HeaderValue, Method};
|
||||
use axum::Router;
|
||||
use sqlx::postgres::PgPoolOptions;
|
||||
use sqlx::PgPool;
|
||||
use tower_http::cors::{AllowOrigin, CorsLayer};
|
||||
use tower_http::trace::TraceLayer;
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::config::{AuthConfig, Config};
|
||||
use crate::storage::{LocalStorage, Storage};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
pub db: PgPool,
|
||||
pub storage: Arc<dyn Storage>,
|
||||
pub auth: AuthConfig,
|
||||
}
|
||||
|
||||
pub async fn build(config: Config) -> anyhow::Result<Router> {
|
||||
@@ -23,7 +26,8 @@ pub async fn build(config: Config) -> anyhow::Result<Router> {
|
||||
|
||||
let storage: Arc<dyn Storage> = Arc::new(LocalStorage::new(config.storage_dir.clone()));
|
||||
|
||||
Ok(router(AppState { db, storage }))
|
||||
let state = AppState { db, storage, auth: config.auth.clone() };
|
||||
Ok(router(state).layer(cors_layer(&config.cors_allowed_origins)))
|
||||
}
|
||||
|
||||
/// Build a router from a pre-assembled state. Used by integration tests
|
||||
@@ -34,3 +38,22 @@ pub fn router(state: AppState) -> Router {
|
||||
.with_state(state)
|
||||
.layer(TraceLayer::new_for_http())
|
||||
}
|
||||
|
||||
fn cors_layer(allowed_origins: &[String]) -> CorsLayer {
|
||||
if allowed_origins.is_empty() {
|
||||
// Same-origin only — no CORS headers emitted.
|
||||
return CorsLayer::new();
|
||||
}
|
||||
let origins: Vec<HeaderValue> = allowed_origins
|
||||
.iter()
|
||||
.filter_map(|o| HeaderValue::from_str(o).ok())
|
||||
.collect();
|
||||
CorsLayer::new()
|
||||
.allow_origin(AllowOrigin::list(origins))
|
||||
.allow_credentials(true)
|
||||
.allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE])
|
||||
.allow_headers([
|
||||
HeaderName::from_static("content-type"),
|
||||
HeaderName::from_static("authorization"),
|
||||
])
|
||||
}
|
||||
|
||||
63
backend/src/auth/extractor.rs
Normal file
63
backend/src/auth/extractor.rs
Normal file
@@ -0,0 +1,63 @@
|
||||
//! `CurrentUser` axum extractor.
|
||||
//!
|
||||
//! Resolves a request to a logged-in user by trying, in order:
|
||||
//! 1. a `mangalord_session` cookie (session lookup by `sha256(value)`);
|
||||
//! 2. an `Authorization: Bearer <token>` header (api_token lookup).
|
||||
//!
|
||||
//! Both paths look up by hash, never by raw value. Failure to resolve
|
||||
//! either way returns 401 via `AppError::Unauthenticated`.
|
||||
|
||||
use axum::async_trait;
|
||||
use axum::extract::FromRequestParts;
|
||||
use axum::http::request::Parts;
|
||||
use axum_extra::extract::cookie::CookieJar;
|
||||
use axum_extra::headers::authorization::Bearer;
|
||||
use axum_extra::headers::Authorization;
|
||||
use axum_extra::TypedHeader;
|
||||
|
||||
use crate::app::AppState;
|
||||
use crate::auth::token::hash_token;
|
||||
use crate::domain::User;
|
||||
use crate::error::AppError;
|
||||
use crate::repo;
|
||||
|
||||
pub const SESSION_COOKIE_NAME: &str = "mangalord_session";
|
||||
|
||||
pub struct CurrentUser(pub User);
|
||||
|
||||
#[async_trait]
|
||||
impl FromRequestParts<AppState> for CurrentUser {
|
||||
type Rejection = AppError;
|
||||
|
||||
async fn from_request_parts(
|
||||
parts: &mut Parts,
|
||||
state: &AppState,
|
||||
) -> Result<Self, Self::Rejection> {
|
||||
let jar = CookieJar::from_headers(&parts.headers);
|
||||
if let Some(cookie) = jar.get(SESSION_COOKIE_NAME) {
|
||||
let hash = hash_token(cookie.value());
|
||||
if let Some(session) = repo::session::find_active(&state.db, &hash).await? {
|
||||
if let Some(user) = repo::user::find_by_id(&state.db, session.user_id).await? {
|
||||
return Ok(CurrentUser(user));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Ok(TypedHeader(Authorization(bearer))) =
|
||||
TypedHeader::<Authorization<Bearer>>::from_request_parts(parts, state).await
|
||||
{
|
||||
let hash = hash_token(bearer.token());
|
||||
if let Some(token) = repo::api_token::find_active(&state.db, &hash).await? {
|
||||
if let Some(user) = repo::user::find_by_id(&state.db, token.user_id).await? {
|
||||
// Fire-and-forget would be ideal but the test harness needs
|
||||
// a deterministic write so the touched timestamp shows up
|
||||
// when the test inspects state. Synchronous is fine.
|
||||
let _ = repo::api_token::touch_last_used(&state.db, token.id).await;
|
||||
return Ok(CurrentUser(user));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err(AppError::Unauthenticated)
|
||||
}
|
||||
}
|
||||
10
backend/src/auth/mod.rs
Normal file
10
backend/src/auth/mod.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
//! Authentication primitives.
|
||||
//!
|
||||
//! Password hashing (argon2id), opaque-token generation for sessions and
|
||||
//! bot API tokens, and the `CurrentUser` axum extractor that resolves a
|
||||
//! request to a logged-in user via either a session cookie or a bearer
|
||||
//! token.
|
||||
|
||||
pub mod extractor;
|
||||
pub mod password;
|
||||
pub mod token;
|
||||
59
backend/src/auth/password.rs
Normal file
59
backend/src/auth/password.rs
Normal file
@@ -0,0 +1,59 @@
|
||||
//! Argon2id password hashing.
|
||||
//!
|
||||
//! `hash_password` returns a PHC-encoded string suitable for storage in
|
||||
//! `users.password_hash`. `verify_password` checks a candidate against a
|
||||
//! stored hash. Default Argon2 params are argon2id with the crate's
|
||||
//! recommended cost (m=19456 KiB, t=2, p=1) — OWASP-aligned.
|
||||
|
||||
use argon2::password_hash::rand_core::OsRng;
|
||||
use argon2::password_hash::{PasswordHash, PasswordHasher, PasswordVerifier, SaltString};
|
||||
use argon2::Argon2;
|
||||
|
||||
use crate::error::{AppError, AppResult};
|
||||
|
||||
pub fn hash_password(plain: &str) -> AppResult<String> {
|
||||
let salt = SaltString::generate(&mut OsRng);
|
||||
Argon2::default()
|
||||
.hash_password(plain.as_bytes(), &salt)
|
||||
.map(|h| h.to_string())
|
||||
.map_err(|e| AppError::Other(anyhow::anyhow!("password hash failed: {e}")))
|
||||
}
|
||||
|
||||
pub fn verify_password(plain: &str, phc: &str) -> bool {
|
||||
let Ok(hash) = PasswordHash::new(phc) else {
|
||||
return false;
|
||||
};
|
||||
Argon2::default()
|
||||
.verify_password(plain.as_bytes(), &hash)
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hash_then_verify_roundtrip() {
|
||||
let phc = hash_password("correct horse battery staple").unwrap();
|
||||
assert!(phc.starts_with("$argon2id$"));
|
||||
assert!(verify_password("correct horse battery staple", &phc));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verify_rejects_wrong_password() {
|
||||
let phc = hash_password("hunter2").unwrap();
|
||||
assert!(!verify_password("hunter3", &phc));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn verify_rejects_malformed_hash() {
|
||||
assert!(!verify_password("anything", "not a real phc string"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hashes_are_salted() {
|
||||
let a = hash_password("same").unwrap();
|
||||
let b = hash_password("same").unwrap();
|
||||
assert_ne!(a, b, "two hashes of the same password must differ (salt)");
|
||||
}
|
||||
}
|
||||
68
backend/src/auth/token.rs
Normal file
68
backend/src/auth/token.rs
Normal file
@@ -0,0 +1,68 @@
|
||||
//! High-entropy opaque tokens for sessions and bot API access.
|
||||
//!
|
||||
//! `generate_token` draws 32 bytes from the OS CSPRNG, encodes them as
|
||||
//! URL-safe base64 (no padding), and returns the raw string alongside its
|
||||
//! SHA-256 hash. Storage holds only the hash; the raw value lives in the
|
||||
//! cookie or `Authorization` header. Comparison goes through
|
||||
//! `constant_time_eq` to keep timing side channels off the table.
|
||||
|
||||
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
|
||||
use base64::Engine as _;
|
||||
use rand::rngs::OsRng;
|
||||
use rand::RngCore;
|
||||
use sha2::{Digest, Sha256};
|
||||
use subtle::ConstantTimeEq;
|
||||
|
||||
pub const TOKEN_BYTES: usize = 32;
|
||||
pub const HASH_BYTES: usize = 32;
|
||||
|
||||
pub fn generate_token() -> (String, [u8; HASH_BYTES]) {
|
||||
let mut raw = [0u8; TOKEN_BYTES];
|
||||
OsRng.fill_bytes(&mut raw);
|
||||
let encoded = URL_SAFE_NO_PAD.encode(raw);
|
||||
let hash = hash_token(&encoded);
|
||||
(encoded, hash)
|
||||
}
|
||||
|
||||
pub fn hash_token(raw: &str) -> [u8; HASH_BYTES] {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(raw.as_bytes());
|
||||
hasher.finalize().into()
|
||||
}
|
||||
|
||||
pub fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
|
||||
a.ct_eq(b).into()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn generates_unique_tokens() {
|
||||
let (a, _) = generate_token();
|
||||
let (b, _) = generate_token();
|
||||
assert_ne!(a, b);
|
||||
// 32 bytes base64url-no-pad → 43 chars.
|
||||
assert_eq!(a.len(), 43);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hash_matches_generated_pair() {
|
||||
let (raw, hash) = generate_token();
|
||||
assert_eq!(hash_token(&raw), hash);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hash_is_deterministic() {
|
||||
assert_eq!(hash_token("abc"), hash_token("abc"));
|
||||
assert_ne!(hash_token("abc"), hash_token("abd"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn constant_time_eq_compares_correctly() {
|
||||
assert!(constant_time_eq(b"abc", b"abc"));
|
||||
assert!(!constant_time_eq(b"abc", b"abd"));
|
||||
assert!(!constant_time_eq(b"abc", b"abcd"));
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,29 @@
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct AuthConfig {
|
||||
pub cookie_secure: bool,
|
||||
pub cookie_domain: Option<String>,
|
||||
pub session_ttl_days: i64,
|
||||
}
|
||||
|
||||
impl Default for AuthConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
cookie_secure: true,
|
||||
cookie_domain: None,
|
||||
session_ttl_days: 30,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Config {
|
||||
pub database_url: String,
|
||||
pub bind_address: String,
|
||||
pub storage_dir: PathBuf,
|
||||
pub auth: AuthConfig,
|
||||
pub cors_allowed_origins: Vec<String>,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
@@ -17,6 +36,37 @@ impl Config {
|
||||
storage_dir: std::env::var("STORAGE_DIR")
|
||||
.unwrap_or_else(|_| "./data/storage".to_string())
|
||||
.into(),
|
||||
auth: AuthConfig {
|
||||
cookie_secure: env_bool("COOKIE_SECURE", true),
|
||||
cookie_domain: std::env::var("COOKIE_DOMAIN")
|
||||
.ok()
|
||||
.filter(|s| !s.is_empty()),
|
||||
session_ttl_days: env_i64("SESSION_TTL_DAYS", 30),
|
||||
},
|
||||
cors_allowed_origins: std::env::var("CORS_ALLOWED_ORIGINS")
|
||||
.ok()
|
||||
.map(|s| {
|
||||
s.split(',')
|
||||
.map(|o| o.trim().to_string())
|
||||
.filter(|o| !o.is_empty())
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn env_bool(name: &str, default: bool) -> bool {
|
||||
match std::env::var(name).ok().as_deref() {
|
||||
Some("1") | Some("true") | Some("TRUE") | Some("yes") => true,
|
||||
Some("0") | Some("false") | Some("FALSE") | Some("no") => false,
|
||||
_ => default,
|
||||
}
|
||||
}
|
||||
|
||||
fn env_i64(name: &str, default: i64) -> i64 {
|
||||
std::env::var(name)
|
||||
.ok()
|
||||
.and_then(|s| s.parse().ok())
|
||||
.unwrap_or(default)
|
||||
}
|
||||
|
||||
15
backend/src/domain/api_token.rs
Normal file
15
backend/src/domain/api_token.rs
Normal file
@@ -0,0 +1,15 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use serde::Serialize;
|
||||
use sqlx::FromRow;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, FromRow)]
|
||||
pub struct ApiToken {
|
||||
pub id: Uuid,
|
||||
pub user_id: Uuid,
|
||||
pub name: String,
|
||||
#[serde(skip)]
|
||||
pub token_hash: Vec<u8>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub last_used_at: Option<DateTime<Utc>>,
|
||||
}
|
||||
@@ -1,9 +1,13 @@
|
||||
pub mod api_token;
|
||||
pub mod bookmark;
|
||||
pub mod chapter;
|
||||
pub mod manga;
|
||||
pub mod session;
|
||||
pub mod user;
|
||||
|
||||
pub use api_token::ApiToken;
|
||||
pub use bookmark::Bookmark;
|
||||
pub use chapter::Chapter;
|
||||
pub use manga::Manga;
|
||||
pub use session::Session;
|
||||
pub use user::User;
|
||||
|
||||
12
backend/src/domain/session.rs
Normal file
12
backend/src/domain/session.rs
Normal file
@@ -0,0 +1,12 @@
|
||||
use chrono::{DateTime, Utc};
|
||||
use sqlx::FromRow;
|
||||
use uuid::Uuid;
|
||||
|
||||
#[derive(Debug, Clone, FromRow)]
|
||||
pub struct Session {
|
||||
pub id: Uuid,
|
||||
pub user_id: Uuid,
|
||||
pub token_hash: Vec<u8>,
|
||||
pub created_at: DateTime<Utc>,
|
||||
pub expires_at: DateTime<Utc>,
|
||||
}
|
||||
@@ -7,5 +7,7 @@ use uuid::Uuid;
|
||||
pub struct User {
|
||||
pub id: Uuid,
|
||||
pub username: String,
|
||||
#[serde(skip)]
|
||||
pub password_hash: String,
|
||||
pub created_at: DateTime<Utc>,
|
||||
}
|
||||
|
||||
@@ -11,6 +11,12 @@ pub enum AppError {
|
||||
NotFound,
|
||||
#[error("invalid input: {0}")]
|
||||
InvalidInput(String),
|
||||
#[error("unauthenticated")]
|
||||
Unauthenticated,
|
||||
#[error("forbidden")]
|
||||
Forbidden,
|
||||
#[error("conflict: {0}")]
|
||||
Conflict(String),
|
||||
#[error(transparent)]
|
||||
Database(#[from] sqlx::Error),
|
||||
#[error(transparent)]
|
||||
@@ -29,6 +35,9 @@ impl AppError {
|
||||
match self {
|
||||
AppError::NotFound => "not_found",
|
||||
AppError::InvalidInput(_) => "invalid_input",
|
||||
AppError::Unauthenticated => "unauthenticated",
|
||||
AppError::Forbidden => "forbidden",
|
||||
AppError::Conflict(_) => "conflict",
|
||||
AppError::Database(sqlx::Error::RowNotFound) => "not_found",
|
||||
AppError::Database(_) => "internal_error",
|
||||
AppError::Storage(StorageError::NotFound) => "not_found",
|
||||
@@ -45,6 +54,9 @@ impl IntoResponse for AppError {
|
||||
let (status, message) = match &self {
|
||||
AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),
|
||||
AppError::InvalidInput(msg) => (StatusCode::BAD_REQUEST, msg.clone()),
|
||||
AppError::Unauthenticated => (StatusCode::UNAUTHORIZED, "unauthenticated".to_string()),
|
||||
AppError::Forbidden => (StatusCode::FORBIDDEN, "forbidden".to_string()),
|
||||
AppError::Conflict(msg) => (StatusCode::CONFLICT, msg.clone()),
|
||||
AppError::Database(sqlx::Error::RowNotFound) => {
|
||||
(StatusCode::NOT_FOUND, "not found".to_string())
|
||||
}
|
||||
@@ -72,6 +84,9 @@ mod tests {
|
||||
fn codes_are_stable() {
|
||||
assert_eq!(AppError::NotFound.code(), "not_found");
|
||||
assert_eq!(AppError::InvalidInput("x".into()).code(), "invalid_input");
|
||||
assert_eq!(AppError::Unauthenticated.code(), "unauthenticated");
|
||||
assert_eq!(AppError::Forbidden.code(), "forbidden");
|
||||
assert_eq!(AppError::Conflict("x".into()).code(), "conflict");
|
||||
assert_eq!(AppError::Storage(StorageError::BadKey).code(), "bad_file_key");
|
||||
assert_eq!(AppError::Storage(StorageError::NotFound).code(), "not_found");
|
||||
assert_eq!(AppError::Database(sqlx::Error::RowNotFound).code(), "not_found");
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
pub mod api;
|
||||
pub mod app;
|
||||
pub mod auth;
|
||||
pub mod config;
|
||||
pub mod domain;
|
||||
pub mod error;
|
||||
|
||||
69
backend/src/repo/api_token.rs
Normal file
69
backend/src/repo/api_token.rs
Normal file
@@ -0,0 +1,69 @@
|
||||
//! Bot API token persistence. `token_hash` is sha256 of the raw bearer
|
||||
//! token; the raw value is shown to the user once at creation and never
|
||||
//! stored.
|
||||
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::domain::ApiToken;
|
||||
use crate::error::AppResult;
|
||||
|
||||
pub async fn create(
|
||||
pool: &PgPool,
|
||||
user_id: Uuid,
|
||||
name: &str,
|
||||
token_hash: &[u8],
|
||||
) -> AppResult<ApiToken> {
|
||||
let row = sqlx::query_as::<_, ApiToken>(
|
||||
r#"
|
||||
INSERT INTO api_tokens (user_id, name, token_hash)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING id, user_id, name, token_hash, created_at, last_used_at
|
||||
"#,
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(name)
|
||||
.bind(token_hash)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
Ok(row)
|
||||
}
|
||||
|
||||
pub async fn find_active(pool: &PgPool, token_hash: &[u8]) -> AppResult<Option<ApiToken>> {
|
||||
let row = sqlx::query_as::<_, ApiToken>(
|
||||
r#"
|
||||
SELECT id, user_id, name, token_hash, created_at, last_used_at
|
||||
FROM api_tokens
|
||||
WHERE token_hash = $1
|
||||
"#,
|
||||
)
|
||||
.bind(token_hash)
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
Ok(row)
|
||||
}
|
||||
|
||||
pub async fn touch_last_used(pool: &PgPool, id: Uuid) -> AppResult<()> {
|
||||
sqlx::query("UPDATE api_tokens SET last_used_at = now() WHERE id = $1")
|
||||
.bind(id)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn find_owner(pool: &PgPool, id: Uuid) -> AppResult<Option<Uuid>> {
|
||||
let row: Option<(Uuid,)> =
|
||||
sqlx::query_as("SELECT user_id FROM api_tokens WHERE id = $1")
|
||||
.bind(id)
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
Ok(row.map(|(uid,)| uid))
|
||||
}
|
||||
|
||||
pub async fn delete(pool: &PgPool, id: Uuid) -> AppResult<()> {
|
||||
sqlx::query("DELETE FROM api_tokens WHERE id = $1")
|
||||
.bind(id)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1 +1,4 @@
|
||||
pub mod api_token;
|
||||
pub mod manga;
|
||||
pub mod session;
|
||||
pub mod user;
|
||||
|
||||
53
backend/src/repo/session.rs
Normal file
53
backend/src/repo/session.rs
Normal file
@@ -0,0 +1,53 @@
|
||||
//! Session persistence. `token_hash` is sha256 of the raw cookie value;
|
||||
//! the raw value never hits the DB.
|
||||
|
||||
use chrono::{DateTime, Utc};
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::domain::Session;
|
||||
use crate::error::AppResult;
|
||||
|
||||
pub async fn create(
|
||||
pool: &PgPool,
|
||||
user_id: Uuid,
|
||||
token_hash: &[u8],
|
||||
expires_at: DateTime<Utc>,
|
||||
) -> AppResult<Session> {
|
||||
let row = sqlx::query_as::<_, Session>(
|
||||
r#"
|
||||
INSERT INTO sessions (user_id, token_hash, expires_at)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING id, user_id, token_hash, created_at, expires_at
|
||||
"#,
|
||||
)
|
||||
.bind(user_id)
|
||||
.bind(token_hash)
|
||||
.bind(expires_at)
|
||||
.fetch_one(pool)
|
||||
.await?;
|
||||
Ok(row)
|
||||
}
|
||||
|
||||
/// Returns the session iff `token_hash` matches and it hasn't expired.
|
||||
pub async fn find_active(pool: &PgPool, token_hash: &[u8]) -> AppResult<Option<Session>> {
|
||||
let row = sqlx::query_as::<_, Session>(
|
||||
r#"
|
||||
SELECT id, user_id, token_hash, created_at, expires_at
|
||||
FROM sessions
|
||||
WHERE token_hash = $1 AND expires_at > now()
|
||||
"#,
|
||||
)
|
||||
.bind(token_hash)
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
Ok(row)
|
||||
}
|
||||
|
||||
pub async fn delete_by_token_hash(pool: &PgPool, token_hash: &[u8]) -> AppResult<()> {
|
||||
sqlx::query("DELETE FROM sessions WHERE token_hash = $1")
|
||||
.bind(token_hash)
|
||||
.execute(pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
57
backend/src/repo/user.rs
Normal file
57
backend/src/repo/user.rs
Normal file
@@ -0,0 +1,57 @@
|
||||
//! User persistence.
|
||||
|
||||
use sqlx::PgPool;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::domain::User;
|
||||
use crate::error::{AppError, AppResult};
|
||||
|
||||
pub async fn create(pool: &PgPool, username: &str, password_hash: &str) -> AppResult<User> {
|
||||
let result = sqlx::query_as::<_, User>(
|
||||
r#"
|
||||
INSERT INTO users (username, password_hash)
|
||||
VALUES ($1, $2)
|
||||
RETURNING id, username, password_hash, created_at
|
||||
"#,
|
||||
)
|
||||
.bind(username)
|
||||
.bind(password_hash)
|
||||
.fetch_one(pool)
|
||||
.await;
|
||||
|
||||
match result {
|
||||
Ok(user) => Ok(user),
|
||||
Err(e) if is_unique_violation(&e) => {
|
||||
Err(AppError::Conflict("username is already taken".into()))
|
||||
}
|
||||
Err(e) => Err(AppError::Database(e)),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn find_by_username(pool: &PgPool, username: &str) -> AppResult<Option<User>> {
|
||||
let row = sqlx::query_as::<_, User>(
|
||||
r#"SELECT id, username, password_hash, created_at FROM users WHERE username = $1"#,
|
||||
)
|
||||
.bind(username)
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
Ok(row)
|
||||
}
|
||||
|
||||
pub async fn find_by_id(pool: &PgPool, id: Uuid) -> AppResult<Option<User>> {
|
||||
let row = sqlx::query_as::<_, User>(
|
||||
r#"SELECT id, username, password_hash, created_at FROM users WHERE id = $1"#,
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
Ok(row)
|
||||
}
|
||||
|
||||
fn is_unique_violation(err: &sqlx::Error) -> bool {
|
||||
if let sqlx::Error::Database(db_err) = err {
|
||||
db_err.code().as_deref() == Some("23505")
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
281
backend/tests/api_auth.rs
Normal file
281
backend/tests/api_auth.rs
Normal file
@@ -0,0 +1,281 @@
|
||||
mod common;
|
||||
|
||||
use axum::http::{header, StatusCode};
|
||||
use serde_json::json;
|
||||
use sqlx::PgPool;
|
||||
use tower::ServiceExt;
|
||||
|
||||
fn creds(username: &str) -> serde_json::Value {
|
||||
json!({ "username": username, "password": "hunter2hunter2" })
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn register_creates_user_and_sets_session_cookie(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::post_json(
|
||||
"/api/v1/auth/register",
|
||||
creds("alice"),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::CREATED);
|
||||
|
||||
let cookie_header = resp
|
||||
.headers()
|
||||
.get(header::SET_COOKIE)
|
||||
.expect("Set-Cookie present")
|
||||
.to_str()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
assert!(cookie_header.starts_with("mangalord_session="));
|
||||
assert!(cookie_header.contains("HttpOnly"));
|
||||
assert!(cookie_header.contains("SameSite=Lax"));
|
||||
assert!(cookie_header.contains("Path=/"));
|
||||
// In the test harness cookie_secure is false; production has Secure.
|
||||
assert!(!cookie_header.contains("Secure"));
|
||||
|
||||
let body = common::body_json(resp).await;
|
||||
assert_eq!(body["user"]["username"], "alice");
|
||||
assert!(body["user"]["id"].as_str().is_some());
|
||||
assert!(
|
||||
body["user"].get("password_hash").is_none(),
|
||||
"password_hash must never leak to the API"
|
||||
);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn register_rejects_duplicate_username_with_conflict(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let _ = h
|
||||
.app
|
||||
.clone()
|
||||
.oneshot(common::post_json("/api/v1/auth/register", creds("alice")))
|
||||
.await
|
||||
.unwrap();
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::post_json("/api/v1/auth/register", creds("alice")))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::CONFLICT);
|
||||
let body = common::body_json(resp).await;
|
||||
assert_eq!(body["error"]["code"], "conflict");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn register_rejects_short_password(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::post_json(
|
||||
"/api/v1/auth/register",
|
||||
json!({ "username": "alice", "password": "short" }),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
let body = common::body_json(resp).await;
|
||||
assert_eq!(body["error"]["code"], "invalid_input");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn login_succeeds_and_rotates_session(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let _ = h
|
||||
.app
|
||||
.clone()
|
||||
.oneshot(common::post_json("/api/v1/auth/register", creds("alice")))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::post_json("/api/v1/auth/login", creds("alice")))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
let cookie = common::extract_session_cookie(&resp).expect("login sets a cookie");
|
||||
assert!(cookie.starts_with("mangalord_session="));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn login_rejects_wrong_password(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let _ = h
|
||||
.app
|
||||
.clone()
|
||||
.oneshot(common::post_json("/api/v1/auth/register", creds("alice")))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::post_json(
|
||||
"/api/v1/auth/login",
|
||||
json!({ "username": "alice", "password": "wrongpassword" }),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
|
||||
let body = common::body_json(resp).await;
|
||||
assert_eq!(body["error"]["code"], "unauthenticated");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn login_rejects_unknown_user(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::post_json("/api/v1/auth/login", creds("ghost")))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn me_returns_user_with_valid_cookie(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let (username, cookie) = common::register_user(&h.app).await;
|
||||
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::get_with_cookie("/api/v1/auth/me", &cookie))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
let body = common::body_json(resp).await;
|
||||
assert_eq!(body["user"]["username"], username);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn me_returns_401_without_cookie(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::get("/api/v1/auth/me"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn logout_clears_session(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let (_, cookie) = common::register_user(&h.app).await;
|
||||
|
||||
let resp = h
|
||||
.app
|
||||
.clone()
|
||||
.oneshot(common::post_json_with_cookie(
|
||||
"/api/v1/auth/logout",
|
||||
json!({}),
|
||||
&cookie,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::NO_CONTENT);
|
||||
|
||||
// Same cookie no longer works.
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::get_with_cookie("/api/v1/auth/me", &cookie))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn create_and_use_bot_token(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let (_, cookie) = common::register_user(&h.app).await;
|
||||
|
||||
let resp = h
|
||||
.app
|
||||
.clone()
|
||||
.oneshot(common::post_json_with_cookie(
|
||||
"/api/v1/auth/tokens",
|
||||
json!({ "name": "ci-bot" }),
|
||||
&cookie,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::CREATED);
|
||||
let body = common::body_json(resp).await;
|
||||
assert_eq!(body["name"], "ci-bot");
|
||||
let bearer = body["bearer"]
|
||||
.as_str()
|
||||
.expect("raw bearer in response")
|
||||
.to_string();
|
||||
assert!(body["token_hash"].is_null(), "token_hash must not leak");
|
||||
|
||||
// Use the bearer to hit /me — should authenticate.
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::get_with_bearer("/api/v1/auth/me", &bearer))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn user_a_cannot_delete_user_b_token(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let (_, cookie_a) = common::register_user(&h.app).await;
|
||||
let (_, cookie_b) = common::register_user(&h.app).await;
|
||||
|
||||
let resp = h
|
||||
.app
|
||||
.clone()
|
||||
.oneshot(common::post_json_with_cookie(
|
||||
"/api/v1/auth/tokens",
|
||||
json!({ "name": "alice-bot" }),
|
||||
&cookie_a,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::CREATED);
|
||||
let body = common::body_json(resp).await;
|
||||
let token_id = body["id"].as_str().unwrap().to_string();
|
||||
|
||||
// User B attempts to delete user A's token → 403.
|
||||
let resp = h
|
||||
.app
|
||||
.clone()
|
||||
.oneshot(common::delete_with_cookie(
|
||||
&format!("/api/v1/auth/tokens/{token_id}"),
|
||||
&cookie_b,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
|
||||
let body = common::body_json(resp).await;
|
||||
assert_eq!(body["error"]["code"], "forbidden");
|
||||
|
||||
// User A succeeds.
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::delete_with_cookie(
|
||||
&format!("/api/v1/auth/tokens/{token_id}"),
|
||||
&cookie_a,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::NO_CONTENT);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn delete_unknown_token_is_404(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let (_, cookie) = common::register_user(&h.app).await;
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::delete_with_cookie(
|
||||
"/api/v1/auth/tokens/00000000-0000-0000-0000-000000000000",
|
||||
&cookie,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
|
||||
}
|
||||
@@ -20,13 +20,15 @@ async fn list_is_empty_initially(pool: PgPool) {
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn create_then_list_roundtrip(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let (_, cookie) = common::register_user(&h.app).await;
|
||||
|
||||
let created = h
|
||||
.app
|
||||
.clone()
|
||||
.oneshot(common::post_json(
|
||||
.oneshot(common::post_json_with_cookie(
|
||||
"/api/v1/mangas",
|
||||
json!({ "title": "Berserk", "author": "Kentaro Miura", "description": null }),
|
||||
&cookie,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -46,6 +48,7 @@ async fn create_then_list_roundtrip(pool: PgPool) {
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn search_filters_by_title_and_author(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let (_, cookie) = common::register_user(&h.app).await;
|
||||
|
||||
for (title, author) in [
|
||||
("One Piece", "Eiichiro Oda"),
|
||||
@@ -55,9 +58,10 @@ async fn search_filters_by_title_and_author(pool: PgPool) {
|
||||
let _ = h
|
||||
.app
|
||||
.clone()
|
||||
.oneshot(common::post_json(
|
||||
.oneshot(common::post_json_with_cookie(
|
||||
"/api/v1/mangas",
|
||||
json!({ "title": title, "author": author }),
|
||||
&cookie,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -96,11 +100,13 @@ async fn search_filters_by_title_and_author(pool: PgPool) {
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn create_rejects_empty_title_with_envelope(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let (_, cookie) = common::register_user(&h.app).await;
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::post_json(
|
||||
.oneshot(common::post_json_with_cookie(
|
||||
"/api/v1/mangas",
|
||||
json!({ "title": " ", "author": null }),
|
||||
&cookie,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
@@ -111,6 +117,22 @@ async fn create_rejects_empty_title_with_envelope(pool: PgPool) {
|
||||
assert!(!msg.is_empty(), "message should be non-empty");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn create_requires_authentication(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::post_json(
|
||||
"/api/v1/mangas",
|
||||
json!({ "title": "Berserk" }),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
|
||||
let body = common::body_json(resp).await;
|
||||
assert_eq!(body["error"]["code"], "unauthenticated");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn get_unknown_id_is_404_with_envelope(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
|
||||
@@ -6,13 +6,16 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::Request;
|
||||
use axum::http::{header, Request};
|
||||
use axum::Router;
|
||||
use http_body_util::BodyExt;
|
||||
use serde_json::json;
|
||||
use sqlx::PgPool;
|
||||
use tempfile::TempDir;
|
||||
use tower::ServiceExt;
|
||||
|
||||
use mangalord::app::{router, AppState};
|
||||
use mangalord::config::AuthConfig;
|
||||
use mangalord::storage::LocalStorage;
|
||||
|
||||
pub struct Harness {
|
||||
@@ -26,6 +29,7 @@ pub fn harness(pool: PgPool) -> Harness {
|
||||
let state = AppState {
|
||||
db: pool,
|
||||
storage: Arc::new(LocalStorage::new(storage_dir.path())),
|
||||
auth: AuthConfig { cookie_secure: false, ..AuthConfig::default() },
|
||||
};
|
||||
Harness { app: router(state), _storage_dir: storage_dir }
|
||||
}
|
||||
@@ -39,11 +43,107 @@ pub fn get(uri: &str) -> Request<Body> {
|
||||
Request::builder().uri(uri).body(Body::empty()).unwrap()
|
||||
}
|
||||
|
||||
pub fn get_with_cookie(uri: &str, cookie: &str) -> Request<Body> {
|
||||
Request::builder()
|
||||
.uri(uri)
|
||||
.header(header::COOKIE, cookie)
|
||||
.body(Body::empty())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub fn get_with_bearer(uri: &str, token: &str) -> Request<Body> {
|
||||
Request::builder()
|
||||
.uri(uri)
|
||||
.header(header::AUTHORIZATION, format!("Bearer {token}"))
|
||||
.body(Body::empty())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub fn post_json(uri: &str, body: serde_json::Value) -> Request<Body> {
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri(uri)
|
||||
.header("content-type", "application/json")
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.body(Body::from(body.to_string()))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub fn post_json_with_cookie(
|
||||
uri: &str,
|
||||
body: serde_json::Value,
|
||||
cookie: &str,
|
||||
) -> Request<Body> {
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri(uri)
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.header(header::COOKIE, cookie)
|
||||
.body(Body::from(body.to_string()))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub fn post_json_with_bearer(
|
||||
uri: &str,
|
||||
body: serde_json::Value,
|
||||
token: &str,
|
||||
) -> Request<Body> {
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri(uri)
|
||||
.header(header::CONTENT_TYPE, "application/json")
|
||||
.header(header::AUTHORIZATION, format!("Bearer {token}"))
|
||||
.body(Body::from(body.to_string()))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
pub fn delete_with_cookie(uri: &str, cookie: &str) -> Request<Body> {
|
||||
Request::builder()
|
||||
.method("DELETE")
|
||||
.uri(uri)
|
||||
.header(header::COOKIE, cookie)
|
||||
.body(Body::empty())
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
/// Extracts the `mangalord_session` cookie from a response's Set-Cookie
|
||||
/// headers as a `name=value` pair suitable for use in a follow-up `Cookie`
|
||||
/// request header. Returns `None` if no such cookie was set.
|
||||
pub fn extract_session_cookie(response: &axum::response::Response) -> Option<String> {
|
||||
response
|
||||
.headers()
|
||||
.get_all(header::SET_COOKIE)
|
||||
.iter()
|
||||
.find_map(|v| {
|
||||
let s = v.to_str().ok()?;
|
||||
if s.starts_with("mangalord_session=") {
|
||||
let end = s.find(';').unwrap_or(s.len());
|
||||
Some(s[..end].to_string())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Register a brand-new user and return (username, session cookie value).
|
||||
/// The username is unique per call so tests can run in parallel against a
|
||||
/// single DB without colliding.
|
||||
pub async fn register_user(app: &Router) -> (String, String) {
|
||||
// 12-hex-digit suffix keeps the username under the 32-char cap.
|
||||
let suffix: String = uuid::Uuid::new_v4().simple().to_string().chars().take(12).collect();
|
||||
let username = format!("u-{suffix}");
|
||||
let resp = app
|
||||
.clone()
|
||||
.oneshot(post_json(
|
||||
"/api/v1/auth/register",
|
||||
json!({ "username": username, "password": "hunter2hunter2" }),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
resp.status(),
|
||||
axum::http::StatusCode::CREATED,
|
||||
"register failed in test harness"
|
||||
);
|
||||
let cookie = extract_session_cookie(&resp).expect("session cookie on register");
|
||||
(username, cookie)
|
||||
}
|
||||
|
||||
102
frontend/e2e/auth-flow.spec.ts
Normal file
102
frontend/e2e/auth-flow.spec.ts
Normal file
@@ -0,0 +1,102 @@
|
||||
import { test, expect, type Page } from '@playwright/test';
|
||||
|
||||
// Mocks the auth endpoints at the network level so the journey is
|
||||
// deterministic and doesn't require a live backend.
|
||||
|
||||
const userFixture = {
|
||||
id: 'user-1',
|
||||
username: 'alice',
|
||||
created_at: '2026-01-01T00:00:00Z'
|
||||
};
|
||||
const emptyPage = { items: [], page: { limit: 50, offset: 0, total: null } };
|
||||
|
||||
async function stubAnonymousThenAuthenticated(page: Page) {
|
||||
let loggedIn = false;
|
||||
await page.route('**/api/v1/auth/me', async (route) => {
|
||||
if (loggedIn) {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ user: userFixture })
|
||||
});
|
||||
} else {
|
||||
await route.fulfill({
|
||||
status: 401,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
error: { code: 'unauthenticated', message: 'unauthenticated' }
|
||||
})
|
||||
});
|
||||
}
|
||||
});
|
||||
await page.route('**/api/v1/auth/login', async (route) => {
|
||||
loggedIn = true;
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ user: userFixture })
|
||||
});
|
||||
});
|
||||
await page.route('**/api/v1/auth/logout', async (route) => {
|
||||
loggedIn = false;
|
||||
await route.fulfill({ status: 204 });
|
||||
});
|
||||
await page.route('**/api/v1/mangas*', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify(emptyPage)
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test('login then logout flips the layout between authenticated and anonymous', async ({
|
||||
page
|
||||
}) => {
|
||||
await stubAnonymousThenAuthenticated(page);
|
||||
|
||||
await page.goto('/');
|
||||
// Initially anonymous → Login / Register links visible.
|
||||
await expect(page.getByTestId('nav-login')).toBeVisible();
|
||||
|
||||
// Log in.
|
||||
await page.goto('/login');
|
||||
await page.getByTestId('login-username').fill('alice');
|
||||
await page.getByTestId('login-password').fill('hunter2hunter2');
|
||||
await page.getByTestId('login-submit').click();
|
||||
|
||||
// Authenticated → username + Logout button.
|
||||
await expect(page.getByTestId('session-user')).toContainText('alice');
|
||||
await expect(page.getByRole('button', { name: 'Logout' })).toBeVisible();
|
||||
|
||||
// Log out.
|
||||
await page.getByRole('button', { name: 'Logout' }).click();
|
||||
await expect(page).toHaveURL(/\/login$/);
|
||||
await expect(page.getByTestId('nav-login')).toBeVisible();
|
||||
});
|
||||
|
||||
test('login surfaces the API error message on bad credentials', async ({ page }) => {
|
||||
await page.route('**/api/v1/auth/me', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 401,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ error: { code: 'unauthenticated', message: 'unauthenticated' } })
|
||||
});
|
||||
});
|
||||
await page.route('**/api/v1/auth/login', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 401,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({
|
||||
error: { code: 'unauthenticated', message: 'unauthenticated' }
|
||||
})
|
||||
});
|
||||
});
|
||||
|
||||
await page.goto('/login');
|
||||
await page.getByTestId('login-username').fill('alice');
|
||||
await page.getByTestId('login-password').fill('wrongpassword');
|
||||
await page.getByTestId('login-submit').click();
|
||||
|
||||
await expect(page.getByTestId('login-error')).toBeVisible();
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { test, expect, type Page } from '@playwright/test';
|
||||
|
||||
// These E2E tests run against the SvelteKit dev server, which proxies /api
|
||||
// to the backend. Playwright starts vite via `webServer` (see
|
||||
@@ -9,7 +9,18 @@ import { test, expect } from '@playwright/test';
|
||||
|
||||
const emptyPage = { items: [], page: { limit: 50, offset: 0, total: null } };
|
||||
|
||||
async function mockAnonymous(page: Page) {
|
||||
await page.route('**/api/v1/auth/me', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 401,
|
||||
contentType: 'application/json',
|
||||
body: JSON.stringify({ error: { code: 'unauthenticated', message: 'unauthenticated' } })
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test('home page renders the Mangalord heading and search input', async ({ page }) => {
|
||||
await mockAnonymous(page);
|
||||
await page.route('**/api/v1/mangas*', async (route) => {
|
||||
await route.fulfill({
|
||||
status: 200,
|
||||
@@ -25,6 +36,7 @@ test('home page renders the Mangalord heading and search input', async ({ page }
|
||||
});
|
||||
|
||||
test('search updates the manga list', async ({ page }) => {
|
||||
await mockAnonymous(page);
|
||||
let lastSearch: string | null = null;
|
||||
await page.route('**/api/v1/mangas*', async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mangalord-frontend",
|
||||
"version": "0.2.0",
|
||||
"version": "0.3.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
142
frontend/src/lib/api/auth.test.ts
Normal file
142
frontend/src/lib/api/auth.test.ts
Normal file
@@ -0,0 +1,142 @@
|
||||
import {
|
||||
describe,
|
||||
it,
|
||||
expect,
|
||||
vi,
|
||||
beforeEach,
|
||||
afterEach,
|
||||
type MockInstance
|
||||
} from 'vitest';
|
||||
import {
|
||||
register,
|
||||
login,
|
||||
logout,
|
||||
me,
|
||||
createToken,
|
||||
deleteToken
|
||||
} from './auth';
|
||||
|
||||
function ok(body: unknown, status = 200): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'content-type': 'application/json' }
|
||||
});
|
||||
}
|
||||
|
||||
function noContent(): Response {
|
||||
return new Response(null, { status: 204 });
|
||||
}
|
||||
|
||||
function envelope(status: number, code: string, message: string): Response {
|
||||
return new Response(JSON.stringify({ error: { code, message } }), {
|
||||
status,
|
||||
headers: { 'content-type': 'application/json' }
|
||||
});
|
||||
}
|
||||
|
||||
const userFixture = {
|
||||
id: 'user-1',
|
||||
username: 'alice',
|
||||
created_at: '2026-01-01T00:00:00Z'
|
||||
};
|
||||
|
||||
describe('auth api client', () => {
|
||||
let fetchSpy: MockInstance<typeof globalThis.fetch>;
|
||||
|
||||
beforeEach(() => {
|
||||
fetchSpy = vi.spyOn(globalThis, 'fetch');
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('register POSTs JSON to /v1/auth/register and returns the user', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(ok({ user: userFixture }, 201));
|
||||
const user = await register({ username: 'alice', password: 'hunter2hunter2' });
|
||||
expect(user).toEqual(userFixture);
|
||||
const url = fetchSpy.mock.calls[0][0] as string;
|
||||
expect(url).toMatch(/\/v1\/auth\/register$/);
|
||||
const init = fetchSpy.mock.calls[0][1] as RequestInit;
|
||||
expect(init.method).toBe('POST');
|
||||
expect(JSON.parse(init.body as string)).toEqual({
|
||||
username: 'alice',
|
||||
password: 'hunter2hunter2'
|
||||
});
|
||||
});
|
||||
|
||||
it('register surfaces 409 conflict via ApiError.code', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(envelope(409, 'conflict', 'username is already taken'));
|
||||
await expect(
|
||||
register({ username: 'alice', password: 'hunter2hunter2' })
|
||||
).rejects.toMatchObject({ status: 409, code: 'conflict' });
|
||||
});
|
||||
|
||||
it('login POSTs JSON to /v1/auth/login and returns the user', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(ok({ user: userFixture }));
|
||||
const user = await login({ username: 'alice', password: 'hunter2hunter2' });
|
||||
expect(user).toEqual(userFixture);
|
||||
const url = fetchSpy.mock.calls[0][0] as string;
|
||||
expect(url).toMatch(/\/v1\/auth\/login$/);
|
||||
});
|
||||
|
||||
it('login surfaces 401 unauthenticated via ApiError.code', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(envelope(401, 'unauthenticated', 'unauthenticated'));
|
||||
await expect(
|
||||
login({ username: 'alice', password: 'wrong' })
|
||||
).rejects.toMatchObject({ status: 401, code: 'unauthenticated' });
|
||||
});
|
||||
|
||||
it('logout POSTs to /v1/auth/logout and handles 204', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(noContent());
|
||||
await expect(logout()).resolves.toBeUndefined();
|
||||
const url = fetchSpy.mock.calls[0][0] as string;
|
||||
expect(url).toMatch(/\/v1\/auth\/logout$/);
|
||||
const init = fetchSpy.mock.calls[0][1] as RequestInit;
|
||||
expect(init.method).toBe('POST');
|
||||
});
|
||||
|
||||
it('me returns the user on 200', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(ok({ user: userFixture }));
|
||||
await expect(me()).resolves.toEqual(userFixture);
|
||||
});
|
||||
|
||||
it('me returns null on 401 (anonymous user)', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(envelope(401, 'unauthenticated', 'unauthenticated'));
|
||||
await expect(me()).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('me re-throws non-401 errors', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(envelope(500, 'internal_error', 'internal error'));
|
||||
await expect(me()).rejects.toMatchObject({ status: 500 });
|
||||
});
|
||||
|
||||
it('createToken POSTs to /v1/auth/tokens and returns CreatedToken with bearer', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(
|
||||
ok(
|
||||
{
|
||||
id: 't1',
|
||||
user_id: 'user-1',
|
||||
name: 'ci-bot',
|
||||
created_at: '2026-01-01T00:00:00Z',
|
||||
last_used_at: null,
|
||||
bearer: 'raw-token-abc'
|
||||
},
|
||||
201
|
||||
)
|
||||
);
|
||||
const t = await createToken('ci-bot');
|
||||
expect(t.name).toBe('ci-bot');
|
||||
expect(t.bearer).toBe('raw-token-abc');
|
||||
const url = fetchSpy.mock.calls[0][0] as string;
|
||||
expect(url).toMatch(/\/v1\/auth\/tokens$/);
|
||||
});
|
||||
|
||||
it('deleteToken DELETEs to /v1/auth/tokens/{id} and handles 204', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(noContent());
|
||||
await expect(deleteToken('t1')).resolves.toBeUndefined();
|
||||
const url = fetchSpy.mock.calls[0][0] as string;
|
||||
expect(url).toMatch(/\/v1\/auth\/tokens\/t1$/);
|
||||
const init = fetchSpy.mock.calls[0][1] as RequestInit;
|
||||
expect(init.method).toBe('DELETE');
|
||||
});
|
||||
});
|
||||
72
frontend/src/lib/api/auth.ts
Normal file
72
frontend/src/lib/api/auth.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { ApiError, request } from './client';
|
||||
|
||||
export type User = {
|
||||
id: string;
|
||||
username: string;
|
||||
created_at: string;
|
||||
};
|
||||
|
||||
export type Credentials = {
|
||||
username: string;
|
||||
password: string;
|
||||
};
|
||||
|
||||
type AuthResponse = { user: User };
|
||||
|
||||
export async function register(creds: Credentials): Promise<User> {
|
||||
const r = await request<AuthResponse>('/v1/auth/register', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(creds)
|
||||
});
|
||||
return r.user;
|
||||
}
|
||||
|
||||
export async function login(creds: Credentials): Promise<User> {
|
||||
const r = await request<AuthResponse>('/v1/auth/login', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(creds)
|
||||
});
|
||||
return r.user;
|
||||
}
|
||||
|
||||
export async function logout(): Promise<void> {
|
||||
await request<void>('/v1/auth/logout', { method: 'POST' });
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current user, or `null` if no valid session.
|
||||
* Re-throws any non-401 error.
|
||||
*/
|
||||
export async function me(): Promise<User | null> {
|
||||
try {
|
||||
const r = await request<AuthResponse>('/v1/auth/me');
|
||||
return r.user;
|
||||
} catch (e) {
|
||||
if (e instanceof ApiError && e.status === 401) return null;
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
export type ApiToken = {
|
||||
id: string;
|
||||
user_id: string;
|
||||
name: string;
|
||||
created_at: string;
|
||||
last_used_at: string | null;
|
||||
};
|
||||
|
||||
export type CreatedToken = ApiToken & { bearer: string };
|
||||
|
||||
export async function createToken(name: string): Promise<CreatedToken> {
|
||||
return request<CreatedToken>('/v1/auth/tokens', {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ name })
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteToken(id: string): Promise<void> {
|
||||
await request<void>(`/v1/auth/tokens/${encodeURIComponent(id)}`, { method: 'DELETE' });
|
||||
}
|
||||
@@ -42,6 +42,9 @@ export async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
}
|
||||
throw new ApiError(res.status, code, message);
|
||||
}
|
||||
if (res.status === 204) {
|
||||
return undefined as T;
|
||||
}
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
|
||||
|
||||
33
frontend/src/lib/session.svelte.ts
Normal file
33
frontend/src/lib/session.svelte.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
// Per-tab session state for the currently logged-in user.
|
||||
//
|
||||
// Only mutated client-side (onMount / form submits) so the module-level
|
||||
// instance can't leak across SSR requests — SSR always renders the
|
||||
// `loaded === false` state, and the client refreshes after hydration.
|
||||
|
||||
import { me, type User } from './api/auth';
|
||||
|
||||
class SessionStore {
|
||||
user = $state<User | null>(null);
|
||||
loaded = $state(false);
|
||||
// Bumped on every explicit setUser so an in-flight refresh started before
|
||||
// a login/logout can't clobber the fresh state when it resolves.
|
||||
private seq = 0;
|
||||
|
||||
async refresh(): Promise<void> {
|
||||
const seq = this.seq;
|
||||
try {
|
||||
const u = await me();
|
||||
if (seq === this.seq) this.user = u;
|
||||
} finally {
|
||||
this.loaded = true;
|
||||
}
|
||||
}
|
||||
|
||||
setUser(user: User | null): void {
|
||||
this.seq++;
|
||||
this.user = user;
|
||||
this.loaded = true;
|
||||
}
|
||||
}
|
||||
|
||||
export const session = new SessionStore();
|
||||
@@ -1,13 +1,47 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { goto } from '$app/navigation';
|
||||
import { logout } from '$lib/api/auth';
|
||||
import { session } from '$lib/session.svelte';
|
||||
|
||||
let { children } = $props();
|
||||
let loggingOut = $state(false);
|
||||
|
||||
onMount(() => {
|
||||
if (!session.loaded) session.refresh();
|
||||
});
|
||||
|
||||
async function handleLogout() {
|
||||
loggingOut = true;
|
||||
try {
|
||||
await logout();
|
||||
} finally {
|
||||
session.setUser(null);
|
||||
loggingOut = false;
|
||||
goto('/login');
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<header>
|
||||
<nav>
|
||||
<nav aria-label="primary">
|
||||
<a href="/">Mangalord</a>
|
||||
<a href="/upload">Upload</a>
|
||||
<a href="/bookmarks">Bookmarks</a>
|
||||
</nav>
|
||||
<div class="session" data-testid="session-area">
|
||||
{#if !session.loaded}
|
||||
<span data-testid="session-loading" aria-busy="true">…</span>
|
||||
{:else if session.user}
|
||||
<span data-testid="session-user">{session.user.username}</span>
|
||||
<button type="button" onclick={handleLogout} disabled={loggingOut}>
|
||||
{loggingOut ? 'Logging out…' : 'Logout'}
|
||||
</button>
|
||||
{:else}
|
||||
<a href="/login" data-testid="nav-login">Login</a>
|
||||
<a href="/register" data-testid="nav-register">Register</a>
|
||||
{/if}
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<main>
|
||||
@@ -18,10 +52,20 @@
|
||||
header {
|
||||
padding: 1rem;
|
||||
border-bottom: 1px solid #ddd;
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
}
|
||||
nav a {
|
||||
nav a,
|
||||
.session a {
|
||||
margin-right: 1rem;
|
||||
}
|
||||
.session {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
main {
|
||||
padding: 1rem;
|
||||
max-width: 64rem;
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
e.preventDefault();
|
||||
load();
|
||||
}}
|
||||
action="javascript:void(0)"
|
||||
>
|
||||
<input
|
||||
type="search"
|
||||
|
||||
72
frontend/src/routes/login/+page.svelte
Normal file
72
frontend/src/routes/login/+page.svelte
Normal file
@@ -0,0 +1,72 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { login } from '$lib/api/auth';
|
||||
import { session } from '$lib/session.svelte';
|
||||
|
||||
let username = $state('');
|
||||
let password = $state('');
|
||||
let error: string | null = $state(null);
|
||||
let submitting = $state(false);
|
||||
|
||||
async function submit(e: SubmitEvent) {
|
||||
e.preventDefault();
|
||||
error = null;
|
||||
submitting = true;
|
||||
try {
|
||||
const user = await login({ username, password });
|
||||
session.setUser(user);
|
||||
await goto('/');
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
} finally {
|
||||
submitting = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<h1>Log in</h1>
|
||||
<form onsubmit={submit} action="javascript:void(0)" data-testid="login-form">
|
||||
<label>
|
||||
Username
|
||||
<input
|
||||
type="text"
|
||||
bind:value={username}
|
||||
autocomplete="username"
|
||||
required
|
||||
data-testid="login-username"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Password
|
||||
<input
|
||||
type="password"
|
||||
bind:value={password}
|
||||
autocomplete="current-password"
|
||||
required
|
||||
data-testid="login-password"
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" disabled={submitting} data-testid="login-submit">
|
||||
{submitting ? 'Logging in…' : 'Log in'}
|
||||
</button>
|
||||
{#if error}
|
||||
<p role="alert" data-testid="login-error">{error}</p>
|
||||
{/if}
|
||||
</form>
|
||||
<p>
|
||||
No account? <a href="/register">Register</a>.
|
||||
</p>
|
||||
|
||||
<style>
|
||||
form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
max-width: 24rem;
|
||||
}
|
||||
label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
</style>
|
||||
75
frontend/src/routes/register/+page.svelte
Normal file
75
frontend/src/routes/register/+page.svelte
Normal file
@@ -0,0 +1,75 @@
|
||||
<script lang="ts">
|
||||
import { goto } from '$app/navigation';
|
||||
import { register } from '$lib/api/auth';
|
||||
import { session } from '$lib/session.svelte';
|
||||
|
||||
let username = $state('');
|
||||
let password = $state('');
|
||||
let error: string | null = $state(null);
|
||||
let submitting = $state(false);
|
||||
|
||||
async function submit(e: SubmitEvent) {
|
||||
e.preventDefault();
|
||||
error = null;
|
||||
submitting = true;
|
||||
try {
|
||||
const user = await register({ username, password });
|
||||
session.setUser(user);
|
||||
await goto('/');
|
||||
} catch (e) {
|
||||
error = (e as Error).message;
|
||||
} finally {
|
||||
submitting = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<h1>Register</h1>
|
||||
<form onsubmit={submit} action="javascript:void(0)" data-testid="register-form">
|
||||
<label>
|
||||
Username
|
||||
<input
|
||||
type="text"
|
||||
bind:value={username}
|
||||
autocomplete="username"
|
||||
minlength="3"
|
||||
maxlength="32"
|
||||
required
|
||||
data-testid="register-username"
|
||||
/>
|
||||
</label>
|
||||
<label>
|
||||
Password
|
||||
<input
|
||||
type="password"
|
||||
bind:value={password}
|
||||
autocomplete="new-password"
|
||||
minlength="8"
|
||||
required
|
||||
data-testid="register-password"
|
||||
/>
|
||||
</label>
|
||||
<button type="submit" disabled={submitting} data-testid="register-submit">
|
||||
{submitting ? 'Registering…' : 'Register'}
|
||||
</button>
|
||||
{#if error}
|
||||
<p role="alert" data-testid="register-error">{error}</p>
|
||||
{/if}
|
||||
</form>
|
||||
<p>
|
||||
Already have an account? <a href="/login">Log in</a>.
|
||||
</p>
|
||||
|
||||
<style>
|
||||
form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
max-width: 24rem;
|
||||
}
|
||||
label {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
</style>
|
||||
Reference in New Issue
Block a user