Spaces:
a
Paused

PNRxA commited on
Commit
2c8ae4e
·
1 Parent(s): dd7a3f0

implement dashboard layout and additional tests

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. api/src/handlers/admin.rs +140 -0
  2. api/src/handlers/mod.rs +1 -0
  3. api/src/id/mod.rs +37 -0
  4. api/src/lib.rs +1 -0
  5. api/src/poster/badge.rs +79 -0
  6. api/src/poster/generate.rs +86 -0
  7. api/src/routes/admin.rs +14 -0
  8. api/src/routes/mod.rs +1 -0
  9. api/src/services/db.rs +133 -35
  10. api/tests/admin.rs +134 -0
  11. api/tests/db_operations.rs +341 -0
  12. api/tests/security.rs +517 -0
  13. web/e2e/api-keys.spec.ts +14 -0
  14. web/e2e/dashboard.spec.ts +58 -0
  15. web/e2e/login-flow.spec.ts +3 -3
  16. web/e2e/posters.spec.ts +41 -0
  17. web/e2e/setup-flow.spec.ts +2 -2
  18. web/package-lock.json +124 -0
  19. web/package.json +3 -0
  20. web/src/__tests__/lib/api.spec.ts +66 -10
  21. web/src/__tests__/router/index.spec.ts +15 -12
  22. web/src/__tests__/stores/auth.spec.ts +84 -0
  23. web/src/__tests__/views/ApiKeysView.spec.ts +34 -34
  24. web/src/__tests__/views/DashboardView.spec.ts +109 -0
  25. web/src/__tests__/views/LoginView.spec.ts +1 -1
  26. web/src/__tests__/views/PostersView.spec.ts +154 -0
  27. web/src/__tests__/views/SetupView.spec.ts +1 -1
  28. web/src/components/AppSidebar.vue +82 -0
  29. web/src/components/RefreshButton.vue +45 -0
  30. web/src/components/ui/badge/Badge.vue +26 -0
  31. web/src/components/ui/badge/index.ts +26 -0
  32. web/src/components/ui/card/Card.vue +22 -0
  33. web/src/components/ui/card/CardAction.vue +17 -0
  34. web/src/components/ui/card/CardContent.vue +17 -0
  35. web/src/components/ui/card/CardDescription.vue +17 -0
  36. web/src/components/ui/card/CardFooter.vue +17 -0
  37. web/src/components/ui/card/CardHeader.vue +17 -0
  38. web/src/components/ui/card/CardTitle.vue +17 -0
  39. web/src/components/ui/card/index.ts +7 -0
  40. web/src/components/ui/dialog/Dialog.vue +19 -0
  41. web/src/components/ui/dialog/DialogClose.vue +15 -0
  42. web/src/components/ui/dialog/DialogContent.vue +53 -0
  43. web/src/components/ui/dialog/DialogDescription.vue +23 -0
  44. web/src/components/ui/dialog/DialogFooter.vue +27 -0
  45. web/src/components/ui/dialog/DialogHeader.vue +17 -0
  46. web/src/components/ui/dialog/DialogOverlay.vue +21 -0
  47. web/src/components/ui/dialog/DialogScrollContent.vue +59 -0
  48. web/src/components/ui/dialog/DialogTitle.vue +23 -0
  49. web/src/components/ui/dialog/DialogTrigger.vue +15 -0
  50. web/src/components/ui/dialog/index.ts +10 -0
api/src/handlers/admin.rs ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use std::sync::Arc;
2
+
3
+ use axum::extract::{Path, Query, State};
4
+ use axum::response::IntoResponse;
5
+ use axum::Json;
6
+ use serde::{Deserialize, Serialize};
7
+
8
+ use crate::cache;
9
+ use crate::error::AppError;
10
+ use crate::services::db;
11
+ use crate::AppState;
12
+
13
+ #[derive(Serialize)]
14
+ pub struct StatsResponse {
15
+ pub total_posters: u64,
16
+ pub total_api_keys: u64,
17
+ pub mem_cache_entries: u64,
18
+ pub id_cache_entries: u64,
19
+ pub ratings_cache_entries: u64,
20
+ pub poster_mem_cache_mb: u64,
21
+ }
22
+
23
+ pub async fn stats(State(state): State<Arc<AppState>>) -> Result<Json<StatsResponse>, AppError> {
24
+ let total_posters = db::count_poster_meta(&state.db).await?;
25
+ let total_api_keys = db::count_api_keys(&state.db).await?;
26
+
27
+ let mem_cache_entries = state.poster_mem_cache.entry_count();
28
+ let id_cache_entries = state.id_cache.entry_count();
29
+ let ratings_cache_entries = state.ratings_cache.entry_count();
30
+ let poster_mem_cache_mb = state.poster_mem_cache.weighted_size() / (1024 * 1024);
31
+
32
+ Ok(Json(StatsResponse {
33
+ total_posters,
34
+ total_api_keys,
35
+ mem_cache_entries,
36
+ id_cache_entries,
37
+ ratings_cache_entries,
38
+ poster_mem_cache_mb,
39
+ }))
40
+ }
41
+
42
+ #[derive(Deserialize)]
43
+ pub struct ListPostersQuery {
44
+ #[serde(default = "default_page")]
45
+ pub page: u64,
46
+ #[serde(default = "default_page_size")]
47
+ pub page_size: u64,
48
+ }
49
+
50
+ fn default_page() -> u64 {
51
+ 1
52
+ }
53
+ fn default_page_size() -> u64 {
54
+ 50
55
+ }
56
+
57
+ #[derive(Serialize)]
58
+ pub struct PosterMetaItem {
59
+ pub cache_key: String,
60
+ pub release_date: Option<String>,
61
+ pub created_at: i64,
62
+ pub updated_at: i64,
63
+ }
64
+
65
+ #[derive(Serialize)]
66
+ pub struct ListPostersResponse {
67
+ pub items: Vec<PosterMetaItem>,
68
+ pub total: u64,
69
+ pub page: u64,
70
+ pub page_size: u64,
71
+ }
72
+
73
+ pub async fn list_posters(
74
+ State(state): State<Arc<AppState>>,
75
+ Query(query): Query<ListPostersQuery>,
76
+ ) -> Result<Json<ListPostersResponse>, AppError> {
77
+ let page = query.page.max(1);
78
+ let page_size = query.page_size.clamp(1, 100);
79
+
80
+ let (items, total) = db::list_poster_meta(&state.db, page, page_size).await?;
81
+
82
+ let items = items
83
+ .into_iter()
84
+ .map(|m| PosterMetaItem {
85
+ cache_key: m.cache_key,
86
+ release_date: m.release_date,
87
+ created_at: m.created_at,
88
+ updated_at: m.updated_at,
89
+ })
90
+ .collect();
91
+
92
+ Ok(Json(ListPostersResponse {
93
+ items,
94
+ total,
95
+ page,
96
+ page_size,
97
+ }))
98
+ }
99
+
100
+ pub async fn poster_image(
101
+ State(state): State<Arc<AppState>>,
102
+ Path((id_type, id_value)): Path<(String, String)>,
103
+ ) -> Result<impl IntoResponse, AppError> {
104
+ // Validate id_type is one of the known variants (imdb, tmdb, tvdb)
105
+ crate::id::IdType::parse(&id_type)?;
106
+
107
+ let path = cache::cache_path(&state.config.cache_dir, &id_type, &id_value);
108
+
109
+ // Canonicalize and verify the resolved path is within cache_dir to prevent traversal
110
+ let canonical_path = tokio::fs::canonicalize(&path).await.map_err(|e| {
111
+ if e.kind() == std::io::ErrorKind::NotFound {
112
+ AppError::IdNotFound(format!("Poster not found: {id_type}/{id_value}"))
113
+ } else {
114
+ tracing::error!(error = %e, path = %path.display(), "Failed to canonicalize poster path");
115
+ AppError::Io(e)
116
+ }
117
+ })?;
118
+ let canonical_cache_dir = tokio::fs::canonicalize(&state.config.cache_dir)
119
+ .await
120
+ .map_err(|e| AppError::Other(format!("Failed to resolve cache dir: {e}")))?;
121
+ if !canonical_path.starts_with(&canonical_cache_dir) {
122
+ return Err(AppError::IdNotFound(format!(
123
+ "Poster not found: {id_type}/{id_value}"
124
+ )));
125
+ }
126
+
127
+ let bytes = tokio::fs::read(&canonical_path).await.map_err(|e| {
128
+ if e.kind() == std::io::ErrorKind::NotFound {
129
+ AppError::IdNotFound(format!("Poster not found: {id_type}/{id_value}"))
130
+ } else {
131
+ tracing::error!(error = %e, path = %canonical_path.display(), "Failed to read poster image");
132
+ AppError::Io(e)
133
+ }
134
+ })?;
135
+
136
+ Ok((
137
+ [(axum::http::header::CONTENT_TYPE, "image/jpeg")],
138
+ bytes,
139
+ ))
140
+ }
api/src/handlers/mod.rs CHANGED
@@ -1,3 +1,4 @@
 
1
  pub mod api_keys;
2
  pub mod auth;
3
  pub mod middleware;
 
1
+ pub mod admin;
2
  pub mod api_keys;
3
  pub mod auth;
4
  pub mod middleware;
api/src/id/mod.rs CHANGED
@@ -152,6 +152,43 @@ async fn resolve_tmdb(id_value: &str, tmdb: &TmdbClient) -> Result<ResolvedId, A
152
  })
153
  }
154
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
  async fn resolve_tvdb(tvdb_id: &str, tmdb: &TmdbClient) -> Result<ResolvedId, AppError> {
156
  let result: FindResult = tmdb
157
  .get(&format!("/find/{tvdb_id}"), &[("external_source", "tvdb_id")])
 
152
  })
153
  }
154
 
155
+ #[cfg(test)]
156
+ mod tests {
157
+ use super::*;
158
+
159
+ #[test]
160
+ fn parse_imdb() {
161
+ assert_eq!(IdType::parse("imdb").unwrap(), IdType::Imdb);
162
+ }
163
+
164
+ #[test]
165
+ fn parse_tmdb() {
166
+ assert_eq!(IdType::parse("tmdb").unwrap(), IdType::Tmdb);
167
+ }
168
+
169
+ #[test]
170
+ fn parse_tvdb() {
171
+ assert_eq!(IdType::parse("tvdb").unwrap(), IdType::Tvdb);
172
+ }
173
+
174
+ #[test]
175
+ fn parse_invalid_id_type() {
176
+ assert!(IdType::parse("invalid").is_err());
177
+ }
178
+
179
+ #[test]
180
+ fn parse_empty_string() {
181
+ assert!(IdType::parse("").is_err());
182
+ }
183
+
184
+ #[test]
185
+ fn parse_case_sensitive() {
186
+ // Should not accept uppercase
187
+ assert!(IdType::parse("IMDB").is_err());
188
+ assert!(IdType::parse("Tmdb").is_err());
189
+ }
190
+ }
191
+
192
  async fn resolve_tvdb(tvdb_id: &str, tmdb: &TmdbClient) -> Result<ResolvedId, AppError> {
193
  let result: FindResult = tmdb
194
  .get(&format!("/find/{tvdb_id}"), &[("external_source", "tvdb_id")])
api/src/lib.rs CHANGED
@@ -83,6 +83,7 @@ pub const SCHEMA_SQL: &[&str] = &[
83
 
84
  pub fn build_app(state: Arc<AppState>) -> Router {
85
  let admin_routes = routes::api_keys::api_key_routes()
 
86
  .route(
87
  "/api/auth/logout",
88
  axum::routing::post(handlers::auth::logout),
 
83
 
84
  pub fn build_app(state: Arc<AppState>) -> Router {
85
  let admin_routes = routes::api_keys::api_key_routes()
86
+ .merge(routes::admin::admin_routes())
87
  .route(
88
  "/api/auth/logout",
89
  axum::routing::post(handlers::auth::logout),
api/src/poster/badge.rs CHANGED
@@ -83,6 +83,85 @@ fn text_width(text: &str, font: &ab_glyph::PxScaleFont<&FontArc>) -> u32 {
83
  width.ceil() as u32
84
  }
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  fn draw_rounded_rect(img: &mut RgbaImage, x: u32, y: u32, w: u32, h: u32, r: u32, color: Rgba<u8>) {
87
  // Simple approach: draw a filled rect and round corners by drawing circles
88
  // For simplicity, just draw the filled rect — true rounded rects need more complex logic
 
83
  width.ceil() as u32
84
  }
85
 
86
+ #[cfg(test)]
87
+ mod tests {
88
+ use super::*;
89
+ use crate::services::ratings::{RatingBadge, RatingSource};
90
+
91
+ fn test_font() -> FontArc {
92
+ FontArc::try_from_slice(crate::FONT_BYTES).unwrap()
93
+ }
94
+
95
+ #[test]
96
+ fn render_badge_correct_height() {
97
+ let badge = RatingBadge {
98
+ source: RatingSource::Imdb,
99
+ value: "8.5".to_string(),
100
+ };
101
+ let img = render_badge(&badge, &test_font());
102
+ assert_eq!(img.height(), BADGE_HEIGHT);
103
+ assert!(img.width() > 0);
104
+ }
105
+
106
+ #[test]
107
+ fn render_badge_all_sources_produce_valid_images() {
108
+ let font = test_font();
109
+ let sources = [
110
+ RatingSource::Imdb,
111
+ RatingSource::Tmdb,
112
+ RatingSource::Rt,
113
+ RatingSource::RtAudience,
114
+ RatingSource::Metacritic,
115
+ RatingSource::Trakt,
116
+ RatingSource::Letterboxd,
117
+ RatingSource::Mal,
118
+ ];
119
+
120
+ for source in sources {
121
+ let badge = RatingBadge {
122
+ source,
123
+ value: "75%".to_string(),
124
+ };
125
+ let img = render_badge(&badge, &font);
126
+ assert_eq!(img.height(), BADGE_HEIGHT, "wrong height for {:?}", source);
127
+ assert!(img.width() > 0, "zero width for {:?}", source);
128
+ }
129
+ }
130
+
131
+ #[test]
132
+ fn render_badge_width_scales_with_value_length() {
133
+ let font = test_font();
134
+ let short = RatingBadge {
135
+ source: RatingSource::Imdb,
136
+ value: "5".to_string(),
137
+ };
138
+ let long = RatingBadge {
139
+ source: RatingSource::Imdb,
140
+ value: "100%".to_string(),
141
+ };
142
+
143
+ let short_img = render_badge(&short, &font);
144
+ let long_img = render_badge(&long, &font);
145
+
146
+ assert!(
147
+ long_img.width() > short_img.width(),
148
+ "longer value should produce wider badge"
149
+ );
150
+ }
151
+
152
+ #[test]
153
+ fn render_badge_empty_value() {
154
+ let font = test_font();
155
+ let badge = RatingBadge {
156
+ source: RatingSource::Tmdb,
157
+ value: String::new(),
158
+ };
159
+ // Should not panic
160
+ let img = render_badge(&badge, &font);
161
+ assert_eq!(img.height(), BADGE_HEIGHT);
162
+ }
163
+ }
164
+
165
  fn draw_rounded_rect(img: &mut RgbaImage, x: u32, y: u32, w: u32, h: u32, r: u32, color: Rgba<u8>) {
166
  // Simple approach: draw a filled rect and round corners by drawing circles
167
  // For simplicity, just draw the filled rect — true rounded rects need more complex logic
api/src/poster/generate.rs CHANGED
@@ -124,3 +124,89 @@ pub fn placeholder_jpeg() -> Vec<u8> {
124
  img.write_with_encoder(encoder).ok();
125
  buf
126
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  img.write_with_encoder(encoder).ok();
125
  buf
126
  }
127
+
128
+ #[cfg(test)]
129
+ mod tests {
130
+ use super::*;
131
+
132
+ #[test]
133
+ fn placeholder_jpeg_produces_valid_jpeg() {
134
+ let bytes = placeholder_jpeg();
135
+ assert!(!bytes.is_empty());
136
+ // JPEG files start with FF D8
137
+ assert_eq!(bytes[0], 0xFF);
138
+ assert_eq!(bytes[1], 0xD8);
139
+ }
140
+
141
+ #[test]
142
+ fn render_poster_no_badges() {
143
+ let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
144
+ // Create a minimal valid PNG in memory
145
+ let img = image::RgbaImage::from_pixel(100, 150, image::Rgba([128, 128, 128, 255]));
146
+ let mut png_bytes = Vec::new();
147
+ let encoder = image::codecs::png::PngEncoder::new(&mut png_bytes);
148
+ image::ImageEncoder::write_image(
149
+ encoder,
150
+ img.as_raw(),
151
+ 100,
152
+ 150,
153
+ image::ExtendedColorType::Rgba8,
154
+ )
155
+ .unwrap();
156
+
157
+ let result = render_poster_sync(&png_bytes, &[], &font, 85).unwrap();
158
+ assert!(!result.is_empty());
159
+ // Should be valid JPEG
160
+ assert_eq!(result[0], 0xFF);
161
+ assert_eq!(result[1], 0xD8);
162
+ }
163
+
164
+ #[test]
165
+ fn render_poster_with_badges() {
166
+ use crate::services::ratings::{RatingBadge, RatingSource};
167
+
168
+ let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
169
+ let img = image::RgbaImage::from_pixel(500, 750, image::Rgba([128, 128, 128, 255]));
170
+ let mut png_bytes = Vec::new();
171
+ let encoder = image::codecs::png::PngEncoder::new(&mut png_bytes);
172
+ image::ImageEncoder::write_image(
173
+ encoder,
174
+ img.as_raw(),
175
+ 500,
176
+ 750,
177
+ image::ExtendedColorType::Rgba8,
178
+ )
179
+ .unwrap();
180
+
181
+ let badges = vec![
182
+ RatingBadge {
183
+ source: RatingSource::Imdb,
184
+ value: "8.5".to_string(),
185
+ },
186
+ RatingBadge {
187
+ source: RatingSource::Tmdb,
188
+ value: "85%".to_string(),
189
+ },
190
+ RatingBadge {
191
+ source: RatingSource::Rt,
192
+ value: "92%".to_string(),
193
+ },
194
+ RatingBadge {
195
+ source: RatingSource::Metacritic,
196
+ value: "78".to_string(),
197
+ },
198
+ ];
199
+
200
+ let result = render_poster_sync(&png_bytes, &badges, &font, 85).unwrap();
201
+ assert!(!result.is_empty());
202
+ assert_eq!(result[0], 0xFF);
203
+ assert_eq!(result[1], 0xD8);
204
+ }
205
+
206
+ #[test]
207
+ fn render_poster_invalid_image_bytes() {
208
+ let font = FontArc::try_from_slice(crate::FONT_BYTES).unwrap();
209
+ let result = render_poster_sync(b"not an image", &[], &font, 85);
210
+ assert!(result.is_err());
211
+ }
212
+ }
api/src/routes/admin.rs ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ use std::sync::Arc;
2
+
3
+ use axum::routing::get;
4
+ use axum::Router;
5
+
6
+ use crate::handlers;
7
+ use crate::AppState;
8
+
9
+ pub fn admin_routes() -> Router<Arc<AppState>> {
10
+ Router::new()
11
+ .route("/api/admin/stats", get(handlers::admin::stats))
12
+ .route("/api/admin/posters", get(handlers::admin::list_posters))
13
+ .route("/api/admin/posters/{id_type}/{id_value}/image", get(handlers::admin::poster_image))
14
+ }
api/src/routes/mod.rs CHANGED
@@ -1,3 +1,4 @@
 
1
  pub mod api_keys;
2
  pub mod auth;
3
  pub mod poster;
 
1
+ pub mod admin;
2
  pub mod api_keys;
3
  pub mod auth;
4
  pub mod poster;
api/src/services/db.rs CHANGED
@@ -4,6 +4,10 @@ use zeroize::Zeroizing;
4
  use crate::entity::{admin_user, api_key, refresh_token};
5
  use crate::error::AppError;
6
 
 
 
 
 
7
  // --- Secret loading from env ---
8
 
9
  pub fn load_secret_from_env(env_var: &str) -> Zeroizing<Vec<u8>> {
@@ -40,9 +44,80 @@ fn hex_to_bytes(hex: &str) -> Result<Vec<u8>, String> {
40
  .collect()
41
  }
42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  // --- Admin user CRUD ---
44
 
45
- pub async fn count_admin_users(db: &DatabaseConnection) -> Result<u64, AppError> {
46
  use sea_orm::PaginatorTrait;
47
  admin_user::Entity::find()
48
  .count(db)
@@ -51,7 +126,7 @@ pub async fn count_admin_users(db: &DatabaseConnection) -> Result<u64, AppError>
51
  }
52
 
53
  pub async fn create_admin_user(
54
- db: &DatabaseConnection,
55
  username: &str,
56
  password_hash: &str,
57
  ) -> Result<admin_user::Model, AppError> {
@@ -59,7 +134,7 @@ pub async fn create_admin_user(
59
  id: Default::default(),
60
  username: Set(username.to_owned()),
61
  password_hash: Set(password_hash.to_owned()),
62
- created_at: Set(chrono::Utc::now().format("%Y-%m-%d %H:%M:%S").to_string()),
63
  };
64
 
65
  let result = admin_user::Entity::insert(model)
@@ -102,7 +177,7 @@ pub async fn create_first_admin_user(
102
  id: Default::default(),
103
  username: Set(username.to_owned()),
104
  password_hash: Set(password_hash.to_owned()),
105
- created_at: Set(chrono::Utc::now().format("%Y-%m-%d %H:%M:%S").to_string()),
106
  };
107
 
108
  let result = admin_user::Entity::insert(model)
@@ -124,7 +199,7 @@ pub async fn create_first_admin_user(
124
  }
125
 
126
  pub async fn find_admin_user_by_username(
127
- db: &DatabaseConnection,
128
  username: &str,
129
  ) -> Result<Option<admin_user::Model>, AppError> {
130
  use sea_orm::ColumnTrait;
@@ -159,7 +234,7 @@ pub async fn create_refresh_token(
159
  user_id: Set(user_id),
160
  token_hash: Set(token_hash.to_owned()),
161
  expires_at: Set(expires_at.to_owned()),
162
- created_at: Set(chrono::Utc::now().format("%Y-%m-%d %H:%M:%S").to_string()),
163
  };
164
 
165
  let result = refresh_token::Entity::insert(model)
@@ -197,7 +272,7 @@ pub async fn delete_refresh_token(db: &impl ConnectionTrait, id: i32) -> Result<
197
  }
198
 
199
  pub async fn delete_refresh_tokens_for_user(
200
- db: &DatabaseConnection,
201
  user_id: i32,
202
  ) -> Result<(), AppError> {
203
  use sea_orm::ColumnTrait;
@@ -211,10 +286,8 @@ pub async fn delete_refresh_tokens_for_user(
211
  Ok(())
212
  }
213
 
214
- pub async fn delete_expired_refresh_tokens(db: &DatabaseConnection) -> Result<u64, AppError> {
215
- let now = chrono::Utc::now()
216
- .format("%Y-%m-%d %H:%M:%S")
217
- .to_string();
218
  use sea_orm::ColumnTrait;
219
  use sea_orm::QueryFilter;
220
  let result = refresh_token::Entity::delete_many()
@@ -229,7 +302,7 @@ pub async fn delete_expired_refresh_tokens(db: &DatabaseConnection) -> Result<u6
229
  // --- API key CRUD ---
230
 
231
  pub async fn create_api_key(
232
- db: &DatabaseConnection,
233
  name: &str,
234
  key_hash: &str,
235
  key_prefix: &str,
@@ -241,7 +314,7 @@ pub async fn create_api_key(
241
  key_hash: Set(key_hash.to_owned()),
242
  key_prefix: Set(key_prefix.to_owned()),
243
  created_by: Set(created_by),
244
- created_at: Set(chrono::Utc::now().format("%Y-%m-%d %H:%M:%S").to_string()),
245
  last_used_at: Set(None),
246
  };
247
 
@@ -258,7 +331,7 @@ pub async fn create_api_key(
258
  }
259
 
260
  pub async fn find_api_key_by_hash(
261
- db: &DatabaseConnection,
262
  key_hash: &str,
263
  ) -> Result<Option<api_key::Model>, AppError> {
264
  use sea_orm::ColumnTrait;
@@ -270,14 +343,14 @@ pub async fn find_api_key_by_hash(
270
  .map_err(|e| AppError::DbError(e.to_string()))
271
  }
272
 
273
- pub async fn list_api_keys(db: &DatabaseConnection) -> Result<Vec<api_key::Model>, AppError> {
274
  api_key::Entity::find()
275
  .all(db)
276
  .await
277
  .map_err(|e| AppError::DbError(e.to_string()))
278
  }
279
 
280
- pub async fn delete_api_key(db: &DatabaseConnection, id: i32) -> Result<(), AppError> {
281
  api_key::Entity::delete_by_id(id)
282
  .exec(db)
283
  .await
@@ -285,32 +358,57 @@ pub async fn delete_api_key(db: &DatabaseConnection, id: i32) -> Result<(), AppE
285
  Ok(())
286
  }
287
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
288
  pub async fn batch_update_last_used(
289
- db: &DatabaseConnection,
290
  ids: &[i32],
291
  ) -> Result<(), AppError> {
292
  if ids.is_empty() {
293
  return Ok(());
294
  }
295
- let now = chrono::Utc::now().format("%Y-%m-%d %H:%M:%S").to_string();
296
- use sea_orm::Statement;
297
  for chunk in ids.chunks(100) {
298
- let placeholders: Vec<&str> = chunk.iter().map(|_| "?").collect();
299
- let sql = format!(
300
- "UPDATE api_keys SET last_used_at = ? WHERE id IN ({})",
301
- placeholders.join(", ")
302
- );
303
- let mut values: Vec<sea_orm::Value> = vec![now.clone().into()];
304
- for &id in chunk {
305
- values.push(id.into());
306
- }
307
- db.execute(Statement::from_sql_and_values(
308
- sea_orm::DatabaseBackend::Sqlite,
309
- &sql,
310
- values,
311
- ))
312
- .await
313
- .map_err(|e| AppError::DbError(e.to_string()))?;
314
  }
315
  Ok(())
316
  }
 
4
  use crate::entity::{admin_user, api_key, refresh_token};
5
  use crate::error::AppError;
6
 
7
+ fn now_utc() -> String {
8
+ chrono::Utc::now().format("%Y-%m-%d %H:%M:%S").to_string()
9
+ }
10
+
11
  // --- Secret loading from env ---
12
 
13
  pub fn load_secret_from_env(env_var: &str) -> Zeroizing<Vec<u8>> {
 
44
  .collect()
45
  }
46
 
47
+ #[cfg(test)]
48
+ mod tests {
49
+ use super::*;
50
+
51
+ #[test]
52
+ fn hex_to_bytes_valid() {
53
+ assert_eq!(hex_to_bytes("abcd").unwrap(), vec![0xab, 0xcd]);
54
+ }
55
+
56
+ #[test]
57
+ fn hex_to_bytes_empty() {
58
+ assert_eq!(hex_to_bytes("").unwrap(), Vec::<u8>::new());
59
+ }
60
+
61
+ #[test]
62
+ fn hex_to_bytes_full_32_bytes() {
63
+ let hex = "00".repeat(32);
64
+ let result = hex_to_bytes(&hex).unwrap();
65
+ assert_eq!(result.len(), 32);
66
+ assert!(result.iter().all(|&b| b == 0));
67
+ }
68
+
69
+ #[test]
70
+ fn hex_to_bytes_odd_length() {
71
+ assert!(hex_to_bytes("abc").is_err());
72
+ }
73
+
74
+ #[test]
75
+ fn hex_to_bytes_invalid_chars() {
76
+ assert!(hex_to_bytes("gg").is_err());
77
+ }
78
+
79
+ #[test]
80
+ fn hex_to_bytes_uppercase() {
81
+ assert_eq!(hex_to_bytes("ABCD").unwrap(), vec![0xab, 0xcd]);
82
+ }
83
+
84
+ #[test]
85
+ fn hex_to_bytes_mixed_case() {
86
+ assert_eq!(hex_to_bytes("aBcD").unwrap(), vec![0xab, 0xcd]);
87
+ }
88
+
89
+ #[test]
90
+ #[should_panic(expected = "is not set")]
91
+ fn load_secret_missing_env_var() {
92
+ load_secret_from_env("OPENPOSTERDB_TEST_NONEXISTENT_SECRET_VAR");
93
+ }
94
+
95
+ #[test]
96
+ #[should_panic(expected = "must be 32 bytes")]
97
+ fn load_secret_wrong_length() {
98
+ let var_name = "OPENPOSTERDB_TEST_SHORT_SECRET";
99
+ unsafe { std::env::set_var(var_name, "abcd") };
100
+ let result = std::panic::catch_unwind(|| load_secret_from_env(var_name));
101
+ unsafe { std::env::remove_var(var_name) };
102
+ if let Err(e) = result {
103
+ std::panic::resume_unwind(e);
104
+ }
105
+ }
106
+
107
+ #[test]
108
+ fn load_secret_valid_32_bytes() {
109
+ let var_name = "OPENPOSTERDB_TEST_VALID_SECRET";
110
+ let hex = "ab".repeat(32);
111
+ unsafe { std::env::set_var(var_name, &hex) };
112
+ let secret = load_secret_from_env(var_name);
113
+ unsafe { std::env::remove_var(var_name) };
114
+ assert_eq!(secret.len(), 32);
115
+ }
116
+ }
117
+
118
  // --- Admin user CRUD ---
119
 
120
+ pub async fn count_admin_users(db: &impl ConnectionTrait) -> Result<u64, AppError> {
121
  use sea_orm::PaginatorTrait;
122
  admin_user::Entity::find()
123
  .count(db)
 
126
  }
127
 
128
  pub async fn create_admin_user(
129
+ db: &impl ConnectionTrait,
130
  username: &str,
131
  password_hash: &str,
132
  ) -> Result<admin_user::Model, AppError> {
 
134
  id: Default::default(),
135
  username: Set(username.to_owned()),
136
  password_hash: Set(password_hash.to_owned()),
137
+ created_at: Set(now_utc()),
138
  };
139
 
140
  let result = admin_user::Entity::insert(model)
 
177
  id: Default::default(),
178
  username: Set(username.to_owned()),
179
  password_hash: Set(password_hash.to_owned()),
180
+ created_at: Set(now_utc()),
181
  };
182
 
183
  let result = admin_user::Entity::insert(model)
 
199
  }
200
 
201
  pub async fn find_admin_user_by_username(
202
+ db: &impl ConnectionTrait,
203
  username: &str,
204
  ) -> Result<Option<admin_user::Model>, AppError> {
205
  use sea_orm::ColumnTrait;
 
234
  user_id: Set(user_id),
235
  token_hash: Set(token_hash.to_owned()),
236
  expires_at: Set(expires_at.to_owned()),
237
+ created_at: Set(now_utc()),
238
  };
239
 
240
  let result = refresh_token::Entity::insert(model)
 
272
  }
273
 
274
  pub async fn delete_refresh_tokens_for_user(
275
+ db: &impl ConnectionTrait,
276
  user_id: i32,
277
  ) -> Result<(), AppError> {
278
  use sea_orm::ColumnTrait;
 
286
  Ok(())
287
  }
288
 
289
+ pub async fn delete_expired_refresh_tokens(db: &impl ConnectionTrait) -> Result<u64, AppError> {
290
+ let now = now_utc();
 
 
291
  use sea_orm::ColumnTrait;
292
  use sea_orm::QueryFilter;
293
  let result = refresh_token::Entity::delete_many()
 
302
  // --- API key CRUD ---
303
 
304
  pub async fn create_api_key(
305
+ db: &impl ConnectionTrait,
306
  name: &str,
307
  key_hash: &str,
308
  key_prefix: &str,
 
314
  key_hash: Set(key_hash.to_owned()),
315
  key_prefix: Set(key_prefix.to_owned()),
316
  created_by: Set(created_by),
317
+ created_at: Set(now_utc()),
318
  last_used_at: Set(None),
319
  };
320
 
 
331
  }
332
 
333
  pub async fn find_api_key_by_hash(
334
+ db: &impl ConnectionTrait,
335
  key_hash: &str,
336
  ) -> Result<Option<api_key::Model>, AppError> {
337
  use sea_orm::ColumnTrait;
 
343
  .map_err(|e| AppError::DbError(e.to_string()))
344
  }
345
 
346
+ pub async fn list_api_keys(db: &impl ConnectionTrait) -> Result<Vec<api_key::Model>, AppError> {
347
  api_key::Entity::find()
348
  .all(db)
349
  .await
350
  .map_err(|e| AppError::DbError(e.to_string()))
351
  }
352
 
353
+ pub async fn delete_api_key(db: &impl ConnectionTrait, id: i32) -> Result<(), AppError> {
354
  api_key::Entity::delete_by_id(id)
355
  .exec(db)
356
  .await
 
358
  Ok(())
359
  }
360
 
361
+ // --- Poster meta queries ---
362
+
363
+ pub async fn count_poster_meta(db: &impl ConnectionTrait) -> Result<u64, AppError> {
364
+ use crate::entity::poster_meta;
365
+ use sea_orm::PaginatorTrait;
366
+ poster_meta::Entity::find()
367
+ .count(db)
368
+ .await
369
+ .map_err(|e| AppError::DbError(e.to_string()))
370
+ }
371
+
372
+ pub async fn count_api_keys(db: &impl ConnectionTrait) -> Result<u64, AppError> {
373
+ use sea_orm::PaginatorTrait;
374
+ api_key::Entity::find()
375
+ .count(db)
376
+ .await
377
+ .map_err(|e| AppError::DbError(e.to_string()))
378
+ }
379
+
380
+ pub async fn list_poster_meta(
381
+ db: &impl ConnectionTrait,
382
+ page: u64,
383
+ page_size: u64,
384
+ ) -> Result<(Vec<crate::entity::poster_meta::Model>, u64), AppError> {
385
+ use crate::entity::poster_meta;
386
+ use sea_orm::PaginatorTrait;
387
+ let paginator = poster_meta::Entity::find().paginate(db, page_size);
388
+ let total = paginator.num_items().await.map_err(|e| AppError::DbError(e.to_string()))?;
389
+ let items = paginator
390
+ .fetch_page(page.saturating_sub(1))
391
+ .await
392
+ .map_err(|e| AppError::DbError(e.to_string()))?;
393
+ Ok((items, total))
394
+ }
395
+
396
  pub async fn batch_update_last_used(
397
+ db: &impl ConnectionTrait,
398
  ids: &[i32],
399
  ) -> Result<(), AppError> {
400
  if ids.is_empty() {
401
  return Ok(());
402
  }
403
+ let now = now_utc();
404
+ use sea_orm::{ColumnTrait, QueryFilter, sea_query::Expr};
405
  for chunk in ids.chunks(100) {
406
+ api_key::Entity::update_many()
407
+ .col_expr(api_key::Column::LastUsedAt, Expr::value(now.clone()))
408
+ .filter(api_key::Column::Id.is_in(chunk.iter().copied()))
409
+ .exec(db)
410
+ .await
411
+ .map_err(|e| AppError::DbError(e.to_string()))?;
 
 
 
 
 
 
 
 
 
 
412
  }
413
  Ok(())
414
  }
api/tests/admin.rs ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ mod common;
2
+
3
+ use axum::body::Body;
4
+ use axum::http::{Request, StatusCode};
5
+ use http_body_util::BodyExt;
6
+ use tower::ServiceExt;
7
+
8
+ #[tokio::test]
9
+ async fn stats_requires_auth() {
10
+ let (app, _state) = common::setup_test_app().await;
11
+
12
+ let req = Request::builder()
13
+ .uri("/api/admin/stats")
14
+ .body(Body::empty())
15
+ .unwrap();
16
+
17
+ let res = app.oneshot(req).await.unwrap();
18
+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
19
+ }
20
+
21
+ #[tokio::test]
22
+ async fn stats_returns_counts() {
23
+ let (app, _state) = common::setup_test_app().await;
24
+ let token = common::setup_admin(&app).await;
25
+
26
+ let req = Request::builder()
27
+ .uri("/api/admin/stats")
28
+ .header("authorization", format!("Bearer {token}"))
29
+ .body(Body::empty())
30
+ .unwrap();
31
+
32
+ let res = app.clone().oneshot(req).await.unwrap();
33
+ assert_eq!(res.status(), StatusCode::OK);
34
+
35
+ let body = res.into_body().collect().await.unwrap().to_bytes();
36
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
37
+
38
+ assert_eq!(json["total_posters"], 0);
39
+ assert_eq!(json["total_api_keys"], 0);
40
+ assert!(json["mem_cache_entries"].is_number());
41
+ assert!(json["id_cache_entries"].is_number());
42
+ assert!(json["ratings_cache_entries"].is_number());
43
+ assert!(json["poster_mem_cache_mb"].is_number());
44
+ }
45
+
46
+ #[tokio::test]
47
+ async fn list_posters_requires_auth() {
48
+ let (app, _state) = common::setup_test_app().await;
49
+
50
+ let req = Request::builder()
51
+ .uri("/api/admin/posters")
52
+ .body(Body::empty())
53
+ .unwrap();
54
+
55
+ let res = app.oneshot(req).await.unwrap();
56
+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
57
+ }
58
+
59
+ #[tokio::test]
60
+ async fn list_posters_returns_empty() {
61
+ let (app, _state) = common::setup_test_app().await;
62
+ let token = common::setup_admin(&app).await;
63
+
64
+ let req = Request::builder()
65
+ .uri("/api/admin/posters?page=1&page_size=10")
66
+ .header("authorization", format!("Bearer {token}"))
67
+ .body(Body::empty())
68
+ .unwrap();
69
+
70
+ let res = app.clone().oneshot(req).await.unwrap();
71
+ assert_eq!(res.status(), StatusCode::OK);
72
+
73
+ let body = res.into_body().collect().await.unwrap().to_bytes();
74
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
75
+
76
+ assert_eq!(json["items"].as_array().unwrap().len(), 0);
77
+ assert_eq!(json["total"], 0);
78
+ assert_eq!(json["page"], 1);
79
+ assert_eq!(json["page_size"], 10);
80
+ }
81
+
82
+ #[tokio::test]
83
+ async fn list_posters_default_pagination() {
84
+ let (app, _state) = common::setup_test_app().await;
85
+ let token = common::setup_admin(&app).await;
86
+
87
+ let req = Request::builder()
88
+ .uri("/api/admin/posters")
89
+ .header("authorization", format!("Bearer {token}"))
90
+ .body(Body::empty())
91
+ .unwrap();
92
+
93
+ let res = app.clone().oneshot(req).await.unwrap();
94
+ assert_eq!(res.status(), StatusCode::OK);
95
+
96
+ let body = res.into_body().collect().await.unwrap().to_bytes();
97
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
98
+
99
+ assert_eq!(json["page"], 1);
100
+ assert_eq!(json["page_size"], 50);
101
+ }
102
+
103
+ #[tokio::test]
104
+ async fn stats_reflects_api_key_count() {
105
+ let (app, _state) = common::setup_test_app().await;
106
+ let token = common::setup_admin(&app).await;
107
+
108
+ // Create an API key
109
+ let req = Request::builder()
110
+ .method("POST")
111
+ .uri("/api/keys")
112
+ .header("content-type", "application/json")
113
+ .header("authorization", format!("Bearer {token}"))
114
+ .body(Body::from(
115
+ serde_json::json!({"name": "test-key"}).to_string(),
116
+ ))
117
+ .unwrap();
118
+ let res = app.clone().oneshot(req).await.unwrap();
119
+ assert_eq!(res.status(), StatusCode::OK);
120
+
121
+ // Check stats
122
+ let req = Request::builder()
123
+ .uri("/api/admin/stats")
124
+ .header("authorization", format!("Bearer {token}"))
125
+ .body(Body::empty())
126
+ .unwrap();
127
+ let res = app.clone().oneshot(req).await.unwrap();
128
+ assert_eq!(res.status(), StatusCode::OK);
129
+
130
+ let body = res.into_body().collect().await.unwrap().to_bytes();
131
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
132
+
133
+ assert_eq!(json["total_api_keys"], 1);
134
+ }
api/tests/db_operations.rs ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ mod common;
2
+
3
+ use openposterdb_api::services::db;
4
+
5
+ // --- Batch last_used_at updates ---
6
+
7
+ #[tokio::test]
8
+ async fn batch_update_last_used_updates_timestamps() {
9
+ let (app, state) = common::setup_test_app().await;
10
+ let token = common::setup_admin(&app).await;
11
+
12
+ use axum::body::Body;
13
+ use axum::http::Request;
14
+ use http_body_util::BodyExt;
15
+ use tower::ServiceExt;
16
+
17
+ // Create two API keys
18
+ let mut key_ids = Vec::new();
19
+ for name in ["key-1", "key-2"] {
20
+ let req = Request::builder()
21
+ .method("POST")
22
+ .uri("/api/keys")
23
+ .header("content-type", "application/json")
24
+ .header("authorization", format!("Bearer {token}"))
25
+ .body(Body::from(
26
+ serde_json::json!({"name": name}).to_string(),
27
+ ))
28
+ .unwrap();
29
+ let res = app.clone().oneshot(req).await.unwrap();
30
+ let body = res.into_body().collect().await.unwrap().to_bytes();
31
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
32
+ key_ids.push(json["id"].as_i64().unwrap() as i32);
33
+ }
34
+
35
+ // Verify last_used_at is initially null
36
+ let keys = db::list_api_keys(&state.db).await.unwrap();
37
+ for key in &keys {
38
+ assert!(key.last_used_at.is_none(), "last_used_at should start null");
39
+ }
40
+
41
+ // Run batch update
42
+ db::batch_update_last_used(&state.db, &key_ids).await.unwrap();
43
+
44
+ // Verify last_used_at is now set
45
+ let keys = db::list_api_keys(&state.db).await.unwrap();
46
+ for key in &keys {
47
+ assert!(
48
+ key.last_used_at.is_some(),
49
+ "last_used_at should be set after batch update"
50
+ );
51
+ }
52
+ }
53
+
54
+ #[tokio::test]
55
+ async fn batch_update_last_used_empty_ids_is_noop() {
56
+ let (_app, state) = common::setup_test_app().await;
57
+
58
+ // Should succeed without error
59
+ db::batch_update_last_used(&state.db, &[]).await.unwrap();
60
+ }
61
+
62
+ #[tokio::test]
63
+ async fn batch_update_last_used_nonexistent_ids_succeeds() {
64
+ let (_app, state) = common::setup_test_app().await;
65
+
66
+ // Should not error even with IDs that don't exist
67
+ db::batch_update_last_used(&state.db, &[999, 1000, 1001])
68
+ .await
69
+ .unwrap();
70
+ }
71
+
72
+ #[tokio::test]
73
+ async fn batch_update_large_chunk() {
74
+ let (app, state) = common::setup_test_app().await;
75
+ let token = common::setup_admin(&app).await;
76
+
77
+ use axum::body::Body;
78
+ use axum::http::Request;
79
+ use http_body_util::BodyExt;
80
+ use tower::ServiceExt;
81
+
82
+ // Create more keys than the chunk size (100)
83
+ let mut key_ids = Vec::new();
84
+ for i in 0..105 {
85
+ let req = Request::builder()
86
+ .method("POST")
87
+ .uri("/api/keys")
88
+ .header("content-type", "application/json")
89
+ .header("authorization", format!("Bearer {token}"))
90
+ .body(Body::from(
91
+ serde_json::json!({"name": format!("key-{i}")}).to_string(),
92
+ ))
93
+ .unwrap();
94
+ let res = app.clone().oneshot(req).await.unwrap();
95
+ let body = res.into_body().collect().await.unwrap().to_bytes();
96
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
97
+ key_ids.push(json["id"].as_i64().unwrap() as i32);
98
+ }
99
+
100
+ // Batch update should handle chunking correctly
101
+ db::batch_update_last_used(&state.db, &key_ids).await.unwrap();
102
+
103
+ // Verify all got updated
104
+ let keys = db::list_api_keys(&state.db).await.unwrap();
105
+ let updated_count = keys.iter().filter(|k| k.last_used_at.is_some()).count();
106
+ assert_eq!(updated_count, 105);
107
+ }
108
+
109
+ // --- Delete expired refresh tokens ---
110
+
111
+ #[tokio::test]
112
+ async fn delete_expired_refresh_tokens_removes_only_expired() {
113
+ let (_app, state) = common::setup_test_app().await;
114
+
115
+ // Create an admin user directly
116
+ let user = db::create_admin_user(
117
+ &state.db,
118
+ "admin",
119
+ "$argon2id$v=19$m=19456,t=2,p=1$fakesalt$fakehash000000000000000000000000",
120
+ )
121
+ .await
122
+ .unwrap();
123
+
124
+ // Create an expired token
125
+ db::create_refresh_token(&state.db, user.id, "expired_hash", "2020-01-01 00:00:00")
126
+ .await
127
+ .unwrap();
128
+
129
+ // Create a valid (future) token
130
+ db::create_refresh_token(&state.db, user.id, "valid_hash", "2099-01-01 00:00:00")
131
+ .await
132
+ .unwrap();
133
+
134
+ // Delete expired
135
+ let deleted = db::delete_expired_refresh_tokens(&state.db).await.unwrap();
136
+ assert_eq!(deleted, 1);
137
+
138
+ // Verify the valid token still exists
139
+ let remaining = db::find_refresh_token_by_hash(&state.db, "valid_hash")
140
+ .await
141
+ .unwrap();
142
+ assert!(remaining.is_some(), "valid token should still exist");
143
+
144
+ // Verify the expired token is gone
145
+ let gone = db::find_refresh_token_by_hash(&state.db, "expired_hash")
146
+ .await
147
+ .unwrap();
148
+ assert!(gone.is_none(), "expired token should be deleted");
149
+ }
150
+
151
+ #[tokio::test]
152
+ async fn delete_expired_refresh_tokens_none_expired() {
153
+ let (_app, state) = common::setup_test_app().await;
154
+
155
+ let deleted = db::delete_expired_refresh_tokens(&state.db).await.unwrap();
156
+ assert_eq!(deleted, 0);
157
+ }
158
+
159
+ // --- API key hash storage ---
160
+
161
+ #[tokio::test]
162
+ async fn api_key_lookup_by_hash() {
163
+ let (_app, state) = common::setup_test_app().await;
164
+
165
+ let user = db::create_admin_user(
166
+ &state.db,
167
+ "admin",
168
+ "$argon2id$v=19$m=19456,t=2,p=1$fakesalt$fakehash000000000000000000000000",
169
+ )
170
+ .await
171
+ .unwrap();
172
+
173
+ // Create a key with known hash
174
+ use sha2::{Digest, Sha256};
175
+ let raw_key = "test_api_key_value_1234567890abcdef";
176
+ let mut hasher = Sha256::new();
177
+ hasher.update(raw_key.as_bytes());
178
+ let key_hash = format!("{:x}", hasher.finalize());
179
+ let key_prefix = &raw_key[..8];
180
+
181
+ db::create_api_key(&state.db, "test-key", &key_hash, key_prefix, user.id)
182
+ .await
183
+ .unwrap();
184
+
185
+ // Look up by hash
186
+ let found = db::find_api_key_by_hash(&state.db, &key_hash)
187
+ .await
188
+ .unwrap();
189
+ assert!(found.is_some());
190
+ let found = found.unwrap();
191
+ assert_eq!(found.name, "test-key");
192
+ assert_eq!(found.key_prefix, key_prefix);
193
+
194
+ // Look up with wrong hash
195
+ let not_found = db::find_api_key_by_hash(&state.db, "0000000000000000")
196
+ .await
197
+ .unwrap();
198
+ assert!(not_found.is_none());
199
+ }
200
+
201
+ // --- Admin user operations ---
202
+
203
+ #[tokio::test]
204
+ async fn create_first_admin_prevents_second() {
205
+ let (_app, state) = common::setup_test_app().await;
206
+
207
+ let result1 = db::create_first_admin_user(
208
+ &state.db,
209
+ "admin1",
210
+ "$argon2id$v=19$m=19456,t=2,p=1$fakesalt$fakehash000000000000000000000000",
211
+ )
212
+ .await;
213
+ assert!(result1.is_ok());
214
+
215
+ let result2 = db::create_first_admin_user(
216
+ &state.db,
217
+ "admin2",
218
+ "$argon2id$v=19$m=19456,t=2,p=1$fakesalt$fakehash000000000000000000000001",
219
+ )
220
+ .await;
221
+ assert!(result2.is_err());
222
+ }
223
+
224
+ #[tokio::test]
225
+ async fn find_admin_by_username_and_id() {
226
+ let (_app, state) = common::setup_test_app().await;
227
+
228
+ let user = db::create_admin_user(
229
+ &state.db,
230
+ "testadmin",
231
+ "$argon2id$v=19$m=19456,t=2,p=1$fakesalt$fakehash000000000000000000000000",
232
+ )
233
+ .await
234
+ .unwrap();
235
+
236
+ // Find by username
237
+ let found = db::find_admin_user_by_username(&state.db, "testadmin")
238
+ .await
239
+ .unwrap();
240
+ assert!(found.is_some());
241
+ assert_eq!(found.unwrap().id, user.id);
242
+
243
+ // Find by id
244
+ let found = db::find_admin_user_by_id(&state.db, user.id)
245
+ .await
246
+ .unwrap();
247
+ assert!(found.is_some());
248
+ assert_eq!(found.unwrap().username, "testadmin");
249
+
250
+ // Not found
251
+ let not_found = db::find_admin_user_by_username(&state.db, "nobody")
252
+ .await
253
+ .unwrap();
254
+ assert!(not_found.is_none());
255
+
256
+ let not_found = db::find_admin_user_by_id(&state.db, 99999)
257
+ .await
258
+ .unwrap();
259
+ assert!(not_found.is_none());
260
+ }
261
+
262
+ // --- Refresh token CRUD ---
263
+
264
+ #[tokio::test]
265
+ async fn refresh_token_create_find_delete() {
266
+ let (_app, state) = common::setup_test_app().await;
267
+
268
+ let user = db::create_admin_user(
269
+ &state.db,
270
+ "admin",
271
+ "$argon2id$v=19$m=19456,t=2,p=1$fakesalt$fakehash000000000000000000000000",
272
+ )
273
+ .await
274
+ .unwrap();
275
+
276
+ // Create
277
+ let token = db::create_refresh_token(
278
+ &state.db,
279
+ user.id,
280
+ "test_token_hash",
281
+ "2099-12-31 23:59:59",
282
+ )
283
+ .await
284
+ .unwrap();
285
+ assert_eq!(token.user_id, user.id);
286
+ assert_eq!(token.token_hash, "test_token_hash");
287
+
288
+ // Find
289
+ let found = db::find_refresh_token_by_hash(&state.db, "test_token_hash")
290
+ .await
291
+ .unwrap();
292
+ assert!(found.is_some());
293
+ assert_eq!(found.unwrap().id, token.id);
294
+
295
+ // Delete
296
+ db::delete_refresh_token(&state.db, token.id)
297
+ .await
298
+ .unwrap();
299
+ let gone = db::find_refresh_token_by_hash(&state.db, "test_token_hash")
300
+ .await
301
+ .unwrap();
302
+ assert!(gone.is_none());
303
+ }
304
+
305
+ #[tokio::test]
306
+ async fn delete_refresh_tokens_for_user_clears_all() {
307
+ let (_app, state) = common::setup_test_app().await;
308
+
309
+ let user = db::create_admin_user(
310
+ &state.db,
311
+ "admin",
312
+ "$argon2id$v=19$m=19456,t=2,p=1$fakesalt$fakehash000000000000000000000000",
313
+ )
314
+ .await
315
+ .unwrap();
316
+
317
+ // Create multiple tokens
318
+ for i in 0..3 {
319
+ db::create_refresh_token(
320
+ &state.db,
321
+ user.id,
322
+ &format!("hash_{i}"),
323
+ "2099-12-31 23:59:59",
324
+ )
325
+ .await
326
+ .unwrap();
327
+ }
328
+
329
+ // Delete all for user
330
+ db::delete_refresh_tokens_for_user(&state.db, user.id)
331
+ .await
332
+ .unwrap();
333
+
334
+ // All should be gone
335
+ for i in 0..3 {
336
+ let found = db::find_refresh_token_by_hash(&state.db, &format!("hash_{i}"))
337
+ .await
338
+ .unwrap();
339
+ assert!(found.is_none());
340
+ }
341
+ }
api/tests/security.rs ADDED
@@ -0,0 +1,517 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ mod common;
2
+
3
+ use std::sync::Mutex;
4
+
5
+ use axum::body::Body;
6
+ use axum::http::{Request, StatusCode};
7
+ use http_body_util::BodyExt;
8
+ use sea_orm::ConnectionTrait;
9
+ use tower::ServiceExt;
10
+
11
+ fn json_body(json: serde_json::Value) -> Body {
12
+ Body::from(json.to_string())
13
+ }
14
+
15
+ // All tests in this file share a process. Since some tests modify the
16
+ // CORS_ORIGIN env var, we must serialize ALL tests to prevent interference.
17
+ static ENV_MUTEX: Mutex<()> = Mutex::new(());
18
+
19
+ fn clear_cors() {
20
+ unsafe { std::env::remove_var("CORS_ORIGIN") };
21
+ }
22
+
23
+ fn set_cors(origin: &str) {
24
+ unsafe { std::env::set_var("CORS_ORIGIN", origin) };
25
+ }
26
+
27
+ // --- CORS origin enforcement ---
28
+
29
+ #[tokio::test]
30
+ async fn cors_post_without_origin_rejected_when_cors_origin_set() {
31
+ let _guard = ENV_MUTEX.lock().unwrap();
32
+ set_cors("https://example.com");
33
+
34
+ let (app, _state) = common::setup_test_app().await;
35
+
36
+ let req = Request::builder()
37
+ .method("POST")
38
+ .uri("/api/auth/setup")
39
+ .header("content-type", "application/json")
40
+ .body(json_body(serde_json::json!({
41
+ "username": "admin",
42
+ "password": "testpassword123"
43
+ })))
44
+ .unwrap();
45
+
46
+ let res = app.oneshot(req).await.unwrap();
47
+ assert_eq!(res.status(), StatusCode::FORBIDDEN);
48
+
49
+ clear_cors();
50
+ }
51
+
52
+ #[tokio::test]
53
+ async fn cors_post_with_wrong_origin_rejected() {
54
+ let _guard = ENV_MUTEX.lock().unwrap();
55
+ set_cors("https://example.com");
56
+
57
+ let (app, _state) = common::setup_test_app().await;
58
+
59
+ let req = Request::builder()
60
+ .method("POST")
61
+ .uri("/api/auth/setup")
62
+ .header("content-type", "application/json")
63
+ .header("origin", "https://evil.com")
64
+ .body(json_body(serde_json::json!({
65
+ "username": "admin",
66
+ "password": "testpassword123"
67
+ })))
68
+ .unwrap();
69
+
70
+ let res = app.oneshot(req).await.unwrap();
71
+ assert_eq!(res.status(), StatusCode::FORBIDDEN);
72
+
73
+ clear_cors();
74
+ }
75
+
76
+ #[tokio::test]
77
+ async fn cors_post_with_correct_origin_allowed() {
78
+ let _guard = ENV_MUTEX.lock().unwrap();
79
+ set_cors("https://example.com");
80
+
81
+ let (app, _state) = common::setup_test_app().await;
82
+
83
+ let req = Request::builder()
84
+ .method("POST")
85
+ .uri("/api/auth/setup")
86
+ .header("content-type", "application/json")
87
+ .header("origin", "https://example.com")
88
+ .body(json_body(serde_json::json!({
89
+ "username": "admin",
90
+ "password": "testpassword123"
91
+ })))
92
+ .unwrap();
93
+
94
+ let res = app.oneshot(req).await.unwrap();
95
+ assert_eq!(res.status(), StatusCode::OK);
96
+
97
+ clear_cors();
98
+ }
99
+
100
+ #[tokio::test]
101
+ async fn cors_get_allowed_even_with_cors_origin_set() {
102
+ let _guard = ENV_MUTEX.lock().unwrap();
103
+ set_cors("https://example.com");
104
+
105
+ let (app, _state) = common::setup_test_app().await;
106
+
107
+ let req = Request::builder()
108
+ .uri("/api/auth/status")
109
+ .body(Body::empty())
110
+ .unwrap();
111
+
112
+ let res = app.oneshot(req).await.unwrap();
113
+ assert_eq!(res.status(), StatusCode::OK);
114
+
115
+ clear_cors();
116
+ }
117
+
118
+ #[tokio::test]
119
+ async fn cors_delete_without_origin_rejected() {
120
+ let _guard = ENV_MUTEX.lock().unwrap();
121
+ set_cors("https://example.com");
122
+
123
+ let (app, _state) = common::setup_test_app().await;
124
+
125
+ let req = Request::builder()
126
+ .method("DELETE")
127
+ .uri("/api/keys/1")
128
+ .header("authorization", "Bearer fake")
129
+ .body(Body::empty())
130
+ .unwrap();
131
+
132
+ let res = app.oneshot(req).await.unwrap();
133
+ assert_eq!(res.status(), StatusCode::FORBIDDEN);
134
+
135
+ clear_cors();
136
+ }
137
+
138
+ // --- Refresh token expiry ---
139
+
140
+ #[tokio::test]
141
+ async fn refresh_with_expired_token_returns_401() {
142
+ let _guard = ENV_MUTEX.lock().unwrap();
143
+ clear_cors();
144
+
145
+ let (app, state) = common::setup_test_app().await;
146
+
147
+ // Setup admin
148
+ let req = Request::builder()
149
+ .method("POST")
150
+ .uri("/api/auth/setup")
151
+ .header("content-type", "application/json")
152
+ .body(json_body(serde_json::json!({
153
+ "username": "admin",
154
+ "password": "testpassword123"
155
+ })))
156
+ .unwrap();
157
+
158
+ let res = app.clone().oneshot(req).await.unwrap();
159
+ assert_eq!(res.status(), StatusCode::OK);
160
+ let set_cookie = common::extract_set_cookie(res.headers()).unwrap();
161
+ let refresh_token = common::extract_refresh_token(&set_cookie).unwrap();
162
+
163
+ // Manually expire all refresh tokens in the DB
164
+ state
165
+ .db
166
+ .execute_unprepared(
167
+ "UPDATE refresh_tokens SET expires_at = '2020-01-01 00:00:00'",
168
+ )
169
+ .await
170
+ .unwrap();
171
+
172
+ // Try to refresh with the expired token
173
+ let req = Request::builder()
174
+ .method("POST")
175
+ .uri("/api/auth/refresh")
176
+ .header("cookie", format!("refresh_token={refresh_token}"))
177
+ .body(Body::empty())
178
+ .unwrap();
179
+
180
+ let res = app.oneshot(req).await.unwrap();
181
+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
182
+ }
183
+
184
+ // --- Concurrent setup race condition ---
185
+
186
+ #[tokio::test]
187
+ async fn concurrent_setup_only_one_succeeds() {
188
+ let _guard = ENV_MUTEX.lock().unwrap();
189
+ clear_cors();
190
+
191
+ let (app, _state) = common::setup_test_app().await;
192
+
193
+ let app1 = app.clone();
194
+ let app2 = app.clone();
195
+
196
+ let req1 = Request::builder()
197
+ .method("POST")
198
+ .uri("/api/auth/setup")
199
+ .header("content-type", "application/json")
200
+ .body(json_body(serde_json::json!({
201
+ "username": "admin1",
202
+ "password": "testpassword123"
203
+ })))
204
+ .unwrap();
205
+
206
+ let req2 = Request::builder()
207
+ .method("POST")
208
+ .uri("/api/auth/setup")
209
+ .header("content-type", "application/json")
210
+ .body(json_body(serde_json::json!({
211
+ "username": "admin2",
212
+ "password": "testpassword123"
213
+ })))
214
+ .unwrap();
215
+
216
+ let (res1, res2) = tokio::join!(app1.oneshot(req1), app2.oneshot(req2));
217
+ let status1 = res1.unwrap().status();
218
+ let status2 = res2.unwrap().status();
219
+
220
+ // Exactly one should succeed, one should fail
221
+ let successes = [status1, status2]
222
+ .iter()
223
+ .filter(|s| **s == StatusCode::OK)
224
+ .count();
225
+ let failures = [status1, status2]
226
+ .iter()
227
+ .filter(|s| **s == StatusCode::FORBIDDEN)
228
+ .count();
229
+
230
+ assert_eq!(successes, 1, "exactly one setup should succeed (got {status1}, {status2})");
231
+ assert_eq!(failures, 1, "exactly one setup should be forbidden (got {status1}, {status2})");
232
+ }
233
+
234
+ // --- API key negative caching ---
235
+
236
+ #[tokio::test]
237
+ async fn invalid_api_key_cached_returns_401_consistently() {
238
+ let _guard = ENV_MUTEX.lock().unwrap();
239
+ clear_cors();
240
+
241
+ let (app, _state) = common::setup_test_app().await;
242
+
243
+ // First request with invalid key
244
+ let req = Request::builder()
245
+ .uri("/bogus-key/imdb/poster-default/tt0000001.jpg")
246
+ .body(Body::empty())
247
+ .unwrap();
248
+ let res = app.clone().oneshot(req).await.unwrap();
249
+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
250
+
251
+ // Second request with same invalid key should also fail (from cache)
252
+ let req = Request::builder()
253
+ .uri("/bogus-key/imdb/poster-default/tt0000001.jpg")
254
+ .body(Body::empty())
255
+ .unwrap();
256
+ let res = app.oneshot(req).await.unwrap();
257
+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
258
+ }
259
+
260
+ // --- Deleted API key is rejected after cache invalidation ---
261
+
262
+ #[tokio::test]
263
+ async fn deleted_api_key_rejected_after_cache_invalidation() {
264
+ let _guard = ENV_MUTEX.lock().unwrap();
265
+ clear_cors();
266
+
267
+ let (app, state) = common::setup_test_app().await;
268
+ let token = common::setup_admin(&app).await;
269
+
270
+ // Create an API key
271
+ let req = Request::builder()
272
+ .method("POST")
273
+ .uri("/api/keys")
274
+ .header("content-type", "application/json")
275
+ .header("authorization", format!("Bearer {token}"))
276
+ .body(json_body(serde_json::json!({"name": "temp-key"})))
277
+ .unwrap();
278
+ let res = app.clone().oneshot(req).await.unwrap();
279
+ let body = res.into_body().collect().await.unwrap().to_bytes();
280
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
281
+ let api_key = json["key"].as_str().unwrap().to_string();
282
+ let key_id = json["id"].as_i64().unwrap();
283
+
284
+ // Use the API key (populates cache)
285
+ let req = Request::builder()
286
+ .uri(format!("/{api_key}/imdb/poster-default/tt0000001.jpg"))
287
+ .body(Body::empty())
288
+ .unwrap();
289
+ let res = app.clone().oneshot(req).await.unwrap();
290
+ assert_ne!(res.status(), StatusCode::UNAUTHORIZED);
291
+
292
+ // Delete the API key via the endpoint (which calls invalidate_all)
293
+ let req = Request::builder()
294
+ .method("DELETE")
295
+ .uri(format!("/api/keys/{key_id}"))
296
+ .header("authorization", format!("Bearer {token}"))
297
+ .body(Body::empty())
298
+ .unwrap();
299
+ let res = app.clone().oneshot(req).await.unwrap();
300
+ assert_eq!(res.status(), StatusCode::OK);
301
+
302
+ // Ensure cache eviction completes
303
+ state.api_key_cache.run_pending_tasks().await;
304
+
305
+ // Now the API key should be rejected
306
+ let req = Request::builder()
307
+ .uri(format!("/{api_key}/imdb/poster-default/tt0000001.jpg"))
308
+ .body(Body::empty())
309
+ .unwrap();
310
+ let res = app.oneshot(req).await.unwrap();
311
+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
312
+ }
313
+
314
+ // --- Input validation on auth endpoints ---
315
+
316
+ #[tokio::test]
317
+ async fn setup_rejects_short_password() {
318
+ let _guard = ENV_MUTEX.lock().unwrap();
319
+ clear_cors();
320
+
321
+ let (app, _state) = common::setup_test_app().await;
322
+
323
+ let req = Request::builder()
324
+ .method("POST")
325
+ .uri("/api/auth/setup")
326
+ .header("content-type", "application/json")
327
+ .body(json_body(serde_json::json!({
328
+ "username": "admin",
329
+ "password": "short"
330
+ })))
331
+ .unwrap();
332
+
333
+ let res = app.oneshot(req).await.unwrap();
334
+ assert_eq!(res.status(), StatusCode::BAD_REQUEST);
335
+ }
336
+
337
+ #[tokio::test]
338
+ async fn setup_rejects_empty_username() {
339
+ let _guard = ENV_MUTEX.lock().unwrap();
340
+ clear_cors();
341
+
342
+ let (app, _state) = common::setup_test_app().await;
343
+
344
+ let req = Request::builder()
345
+ .method("POST")
346
+ .uri("/api/auth/setup")
347
+ .header("content-type", "application/json")
348
+ .body(json_body(serde_json::json!({
349
+ "username": "",
350
+ "password": "testpassword123"
351
+ })))
352
+ .unwrap();
353
+
354
+ let res = app.oneshot(req).await.unwrap();
355
+ assert_eq!(res.status(), StatusCode::BAD_REQUEST);
356
+ }
357
+
358
+ #[tokio::test]
359
+ async fn setup_rejects_username_with_whitespace() {
360
+ let _guard = ENV_MUTEX.lock().unwrap();
361
+ clear_cors();
362
+
363
+ let (app, _state) = common::setup_test_app().await;
364
+
365
+ let req = Request::builder()
366
+ .method("POST")
367
+ .uri("/api/auth/setup")
368
+ .header("content-type", "application/json")
369
+ .body(json_body(serde_json::json!({
370
+ "username": "admin user",
371
+ "password": "testpassword123"
372
+ })))
373
+ .unwrap();
374
+
375
+ let res = app.oneshot(req).await.unwrap();
376
+ assert_eq!(res.status(), StatusCode::BAD_REQUEST);
377
+ }
378
+
379
+ // --- Expired JWT token ---
380
+
381
+ #[tokio::test]
382
+ async fn expired_jwt_rejected() {
383
+ let _guard = ENV_MUTEX.lock().unwrap();
384
+ clear_cors();
385
+
386
+ let (app, state) = common::setup_test_app().await;
387
+
388
+ let claims = serde_json::json!({
389
+ "sub": "admin",
390
+ "exp": 1000000000 // Way in the past (2001)
391
+ });
392
+
393
+ let token = jsonwebtoken::encode(
394
+ &jsonwebtoken::Header::default(),
395
+ &claims,
396
+ &jsonwebtoken::EncodingKey::from_secret(&state.jwt_secret),
397
+ )
398
+ .unwrap();
399
+
400
+ let req = Request::builder()
401
+ .uri("/api/keys")
402
+ .header("authorization", format!("Bearer {token}"))
403
+ .body(Body::empty())
404
+ .unwrap();
405
+
406
+ let res = app.oneshot(req).await.unwrap();
407
+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
408
+ }
409
+
410
+ // --- JWT signed with wrong secret ---
411
+
412
+ #[tokio::test]
413
+ async fn jwt_with_wrong_secret_rejected() {
414
+ let _guard = ENV_MUTEX.lock().unwrap();
415
+ clear_cors();
416
+
417
+ let (app, _state) = common::setup_test_app().await;
418
+
419
+ let wrong_secret = vec![0xCD; 32];
420
+ let exp = (chrono::Utc::now() + chrono::Duration::hours(1)).timestamp() as usize;
421
+
422
+ let claims = serde_json::json!({
423
+ "sub": "admin",
424
+ "exp": exp
425
+ });
426
+
427
+ let token = jsonwebtoken::encode(
428
+ &jsonwebtoken::Header::default(),
429
+ &claims,
430
+ &jsonwebtoken::EncodingKey::from_secret(&wrong_secret),
431
+ )
432
+ .unwrap();
433
+
434
+ let req = Request::builder()
435
+ .uri("/api/keys")
436
+ .header("authorization", format!("Bearer {token}"))
437
+ .body(Body::empty())
438
+ .unwrap();
439
+
440
+ let res = app.oneshot(req).await.unwrap();
441
+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
442
+ }
443
+
444
+ // --- Poster endpoint with invalid id type ---
445
+
446
+ #[tokio::test]
447
+ async fn poster_endpoint_invalid_id_type() {
448
+ let _guard = ENV_MUTEX.lock().unwrap();
449
+ clear_cors();
450
+
451
+ let (app, _state) = common::setup_test_app().await;
452
+ let token = common::setup_admin(&app).await;
453
+
454
+ // Create a valid API key
455
+ let req = Request::builder()
456
+ .method("POST")
457
+ .uri("/api/keys")
458
+ .header("content-type", "application/json")
459
+ .header("authorization", format!("Bearer {token}"))
460
+ .body(json_body(serde_json::json!({"name": "test"})))
461
+ .unwrap();
462
+ let res = app.clone().oneshot(req).await.unwrap();
463
+ let body = res.into_body().collect().await.unwrap().to_bytes();
464
+ let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
465
+ let api_key = json["key"].as_str().unwrap();
466
+
467
+ // Use invalid id type
468
+ let req = Request::builder()
469
+ .uri(format!("/{api_key}/invalid_type/poster-default/tt0000001.jpg"))
470
+ .body(Body::empty())
471
+ .unwrap();
472
+
473
+ let res = app.oneshot(req).await.unwrap();
474
+ assert_eq!(res.status(), StatusCode::BAD_REQUEST);
475
+ }
476
+
477
+ // --- Refresh with fabricated token (not in DB) ---
478
+
479
+ #[tokio::test]
480
+ async fn refresh_with_fabricated_token_returns_401() {
481
+ let _guard = ENV_MUTEX.lock().unwrap();
482
+ clear_cors();
483
+
484
+ let (app, _state) = common::setup_test_app().await;
485
+ common::setup_admin(&app).await;
486
+
487
+ let req = Request::builder()
488
+ .method("POST")
489
+ .uri("/api/auth/refresh")
490
+ .header("cookie", "refresh_token=aabbccdd00112233fabricatedtoken")
491
+ .body(Body::empty())
492
+ .unwrap();
493
+
494
+ let res = app.oneshot(req).await.unwrap();
495
+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
496
+ }
497
+
498
+ // --- Delete nonexistent API key ---
499
+
500
+ #[tokio::test]
501
+ async fn delete_nonexistent_api_key_succeeds() {
502
+ let _guard = ENV_MUTEX.lock().unwrap();
503
+ clear_cors();
504
+
505
+ let (app, _state) = common::setup_test_app().await;
506
+ let token = common::setup_admin(&app).await;
507
+
508
+ let req = Request::builder()
509
+ .method("DELETE")
510
+ .uri("/api/keys/99999")
511
+ .header("authorization", format!("Bearer {token}"))
512
+ .body(Body::empty())
513
+ .unwrap();
514
+
515
+ let res = app.oneshot(req).await.unwrap();
516
+ assert_eq!(res.status(), StatusCode::OK);
517
+ }
web/e2e/api-keys.spec.ts CHANGED
@@ -11,6 +11,10 @@ test.describe('api keys', () => {
11
  await page.fill('#username', 'admin')
12
  await page.fill('#password', 'testpassword123')
13
  await page.click('button[type="submit"]')
 
 
 
 
14
  await expect(page).toHaveURL(/\/keys/)
15
  })
16
 
@@ -40,6 +44,16 @@ test.describe('api keys', () => {
40
  await expect(page.locator('text=my-prod-key')).toBeVisible()
41
  })
42
 
 
 
 
 
 
 
 
 
 
 
43
  test('delete a key removes it from list', async ({ page }) => {
44
  // Create a key
45
  await page.fill('input[placeholder*="Key name"]', 'to-delete')
 
11
  await page.fill('#username', 'admin')
12
  await page.fill('#password', 'testpassword123')
13
  await page.click('button[type="submit"]')
14
+ await expect(page).toHaveURL(/\/$/)
15
+
16
+ // Navigate to API Keys page
17
+ await page.click('text=API Keys')
18
  await expect(page).toHaveURL(/\/keys/)
19
  })
20
 
 
44
  await expect(page.locator('text=my-prod-key')).toBeVisible()
45
  })
46
 
47
+ test('refresh button is visible and clickable', async ({ page }) => {
48
+ const refreshButton = page.locator('button:has-text("Refresh")')
49
+ await expect(refreshButton).toBeVisible()
50
+
51
+ await refreshButton.click()
52
+
53
+ // Button should still be present after refresh completes
54
+ await expect(refreshButton).toBeVisible()
55
+ })
56
+
57
  test('delete a key removes it from list', async ({ page }) => {
58
  // Create a key
59
  await page.fill('input[placeholder*="Key name"]', 'to-delete')
web/e2e/dashboard.spec.ts ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { test, expect } from '@playwright/test'
2
+
3
+ test.describe('dashboard', () => {
4
+ test.beforeEach(async ({ page, request }) => {
5
+ await request.post('/api/auth/setup', {
6
+ data: { username: 'admin', password: 'testpassword123' },
7
+ })
8
+
9
+ await page.goto('/login')
10
+ await page.fill('#username', 'admin')
11
+ await page.fill('#password', 'testpassword123')
12
+ await page.click('button[type="submit"]')
13
+ await expect(page).toHaveURL(/\/$/)
14
+ })
15
+
16
+ test('shows stats cards', async ({ page }) => {
17
+ const cards = page.locator('[data-slot="card"]')
18
+ await expect(cards.filter({ hasText: 'Total Posters' })).toBeVisible()
19
+ await expect(cards.filter({ hasText: 'API Keys' })).toBeVisible()
20
+ await expect(cards.filter({ hasText: 'Memory Cache Entries' })).toBeVisible()
21
+ await expect(cards.filter({ hasText: 'ID Cache Entries' })).toBeVisible()
22
+ await expect(cards.filter({ hasText: 'Ratings Cache Entries' })).toBeVisible()
23
+ await expect(cards.filter({ hasText: 'Poster Cache (MB)' })).toBeVisible()
24
+ })
25
+
26
+ test('refresh button fetches new data', async ({ page }) => {
27
+ await expect(page.locator('text=Total Posters')).toBeVisible()
28
+
29
+ await page.click('button:has-text("Refresh")')
30
+
31
+ // After refresh, the check icon should briefly appear
32
+ await expect(page.locator('text=Refresh')).toBeVisible()
33
+ })
34
+
35
+ test('clicking OpenPosterDB title navigates to dashboard', async ({ page }) => {
36
+ // Navigate away first
37
+ await page.click('text=Posters')
38
+ await expect(page).toHaveURL(/\/posters/)
39
+
40
+ // Click the title
41
+ await page.click('text=OpenPosterDB')
42
+ await expect(page).toHaveURL(/\/$/)
43
+ })
44
+
45
+ test('sidebar navigation works', async ({ page }) => {
46
+ // Navigate to Posters
47
+ await page.click('text=Posters')
48
+ await expect(page).toHaveURL(/\/posters/)
49
+
50
+ // Navigate to API Keys
51
+ await page.click('text=API Keys')
52
+ await expect(page).toHaveURL(/\/keys/)
53
+
54
+ // Navigate back to Dashboard
55
+ await page.click('text=Dashboard')
56
+ await expect(page).toHaveURL(/\/$/)
57
+ })
58
+ })
web/e2e/login-flow.spec.ts CHANGED
@@ -14,7 +14,7 @@ test.describe('login flow', () => {
14
  await page.fill('#password', 'testpassword123')
15
  await page.click('button[type="submit"]')
16
 
17
- await expect(page).toHaveURL(/\/keys/)
18
  })
19
 
20
  test('login with invalid credentials shows error', async ({ page, request }) => {
@@ -41,9 +41,9 @@ test.describe('login flow', () => {
41
  await page.fill('#username', 'admin')
42
  await page.fill('#password', 'testpassword123')
43
  await page.click('button[type="submit"]')
44
- await expect(page).toHaveURL(/\/keys/)
45
 
46
- // Click logout
47
  await page.click('text=Sign out')
48
  await expect(page).toHaveURL(/\/login/)
49
  })
 
14
  await page.fill('#password', 'testpassword123')
15
  await page.click('button[type="submit"]')
16
 
17
+ await expect(page).toHaveURL(/\/$/)
18
  })
19
 
20
  test('login with invalid credentials shows error', async ({ page, request }) => {
 
41
  await page.fill('#username', 'admin')
42
  await page.fill('#password', 'testpassword123')
43
  await page.click('button[type="submit"]')
44
+ await expect(page).toHaveURL(/\/$/)
45
 
46
+ // Click logout in sidebar
47
  await page.click('text=Sign out')
48
  await expect(page).toHaveURL(/\/login/)
49
  })
web/e2e/posters.spec.ts ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { test, expect } from '@playwright/test'
2
+
3
+ test.describe('posters page', () => {
4
+ test.beforeEach(async ({ page, request }) => {
5
+ await request.post('/api/auth/setup', {
6
+ data: { username: 'admin', password: 'testpassword123' },
7
+ })
8
+
9
+ await page.goto('/login')
10
+ await page.fill('#username', 'admin')
11
+ await page.fill('#password', 'testpassword123')
12
+ await page.click('button[type="submit"]')
13
+ await expect(page).toHaveURL(/\/$/)
14
+
15
+ await page.click('text=Posters')
16
+ await expect(page).toHaveURL(/\/posters/)
17
+ })
18
+
19
+ test('shows table headers', async ({ page }) => {
20
+ await expect(page.locator('th:has-text("ID Type")')).toBeVisible()
21
+ await expect(page.locator('th:has-text("ID Value")')).toBeVisible()
22
+ await expect(page.locator('th:has-text("Release Date")')).toBeVisible()
23
+ await expect(page.locator('th:has-text("Last Updated")')).toBeVisible()
24
+ await expect(page.locator('th:has-text("Created")')).toBeVisible()
25
+ })
26
+
27
+ test('shows empty state when no posters', async ({ page }) => {
28
+ await expect(page.getByRole('cell', { name: 'No posters cached yet.' })).toBeVisible()
29
+ await expect(page.getByText('0 posters total')).toBeVisible()
30
+ })
31
+
32
+ test('has refresh button', async ({ page }) => {
33
+ await expect(page.locator('button:has-text("Refresh")')).toBeVisible()
34
+ })
35
+
36
+ test('has pagination controls', async ({ page }) => {
37
+ await expect(page.locator('button:has-text("Previous")')).toBeVisible()
38
+ await expect(page.locator('button:has-text("Next")')).toBeVisible()
39
+ await expect(page.locator('text=/Page \\d+ of \\d+/')).toBeVisible()
40
+ })
41
+ })
web/e2e/setup-flow.spec.ts CHANGED
@@ -6,7 +6,7 @@ test.describe.serial('setup flow', () => {
6
  await expect(page).toHaveURL(/\/setup/)
7
  })
8
 
9
- test('create admin account and redirect to /keys', async ({ page }) => {
10
  await page.goto('/setup')
11
 
12
  await page.fill('#username', 'admin')
@@ -14,7 +14,7 @@ test.describe.serial('setup flow', () => {
14
  await page.fill('#confirm-password', 'testpassword123')
15
  await page.click('button[type="submit"]')
16
 
17
- await expect(page).toHaveURL(/\/keys/)
18
  })
19
 
20
  test('revisiting /setup after account created redirects to /login', async ({ page }) => {
 
6
  await expect(page).toHaveURL(/\/setup/)
7
  })
8
 
9
+ test('create admin account and redirect to dashboard', async ({ page }) => {
10
  await page.goto('/setup')
11
 
12
  await page.fill('#username', 'admin')
 
14
  await page.fill('#confirm-password', 'testpassword123')
15
  await page.click('button[type="submit"]')
16
 
17
+ await expect(page).toHaveURL(/\/$/)
18
  })
19
 
20
  test('revisiting /setup after account created redirects to /login', async ({ page }) => {
web/package-lock.json CHANGED
@@ -9,6 +9,9 @@
9
  "version": "0.1.0",
10
  "dependencies": {
11
  "@tailwindcss/vite": "^4.2.1",
 
 
 
12
  "class-variance-authority": "^0.7.1",
13
  "clsx": "^2.1.1",
14
  "lucide-vue-next": "^0.577.0",
@@ -2787,6 +2790,45 @@
2787
  "vite": "^5.2.0 || ^6 || ^7"
2788
  }
2789
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2790
  "node_modules/@tanstack/virtual-core": {
2791
  "version": "3.13.21",
2792
  "resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.13.21.tgz",
@@ -2797,6 +2839,82 @@
2797
  "url": "https://github.com/sponsors/tannerlinsley"
2798
  }
2799
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2800
  "node_modules/@tanstack/vue-virtual": {
2801
  "version": "3.13.21",
2802
  "resolved": "https://registry.npmjs.org/@tanstack/vue-virtual/-/vue-virtual-3.13.21.tgz",
@@ -6528,6 +6646,12 @@
6528
  "vue": ">= 3.4.0"
6529
  }
6530
  },
 
 
 
 
 
 
6531
  "node_modules/require-from-string": {
6532
  "version": "2.0.2",
6533
  "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
 
9
  "version": "0.1.0",
10
  "dependencies": {
11
  "@tailwindcss/vite": "^4.2.1",
12
+ "@tanstack/vue-query": "^5.92.9",
13
+ "@tanstack/vue-table": "^8.21.3",
14
+ "@vueuse/core": "^14.2.1",
15
  "class-variance-authority": "^0.7.1",
16
  "clsx": "^2.1.1",
17
  "lucide-vue-next": "^0.577.0",
 
2790
  "vite": "^5.2.0 || ^6 || ^7"
2791
  }
2792
  },
2793
+ "node_modules/@tanstack/match-sorter-utils": {
2794
+ "version": "8.19.4",
2795
+ "resolved": "https://registry.npmjs.org/@tanstack/match-sorter-utils/-/match-sorter-utils-8.19.4.tgz",
2796
+ "integrity": "sha512-Wo1iKt2b9OT7d+YGhvEPD3DXvPv2etTusIMhMUoG7fbhmxcXCtIjJDEygy91Y2JFlwGyjqiBPRozme7UD8hoqg==",
2797
+ "license": "MIT",
2798
+ "dependencies": {
2799
+ "remove-accents": "0.5.0"
2800
+ },
2801
+ "engines": {
2802
+ "node": ">=12"
2803
+ },
2804
+ "funding": {
2805
+ "type": "github",
2806
+ "url": "https://github.com/sponsors/tannerlinsley"
2807
+ }
2808
+ },
2809
+ "node_modules/@tanstack/query-core": {
2810
+ "version": "5.90.20",
2811
+ "resolved": "https://registry.npmjs.org/@tanstack/query-core/-/query-core-5.90.20.tgz",
2812
+ "integrity": "sha512-OMD2HLpNouXEfZJWcKeVKUgQ5n+n3A2JFmBaScpNDUqSrQSjiveC7dKMe53uJUg1nDG16ttFPz2xfilz6i2uVg==",
2813
+ "license": "MIT",
2814
+ "funding": {
2815
+ "type": "github",
2816
+ "url": "https://github.com/sponsors/tannerlinsley"
2817
+ }
2818
+ },
2819
+ "node_modules/@tanstack/table-core": {
2820
+ "version": "8.21.3",
2821
+ "resolved": "https://registry.npmjs.org/@tanstack/table-core/-/table-core-8.21.3.tgz",
2822
+ "integrity": "sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg==",
2823
+ "license": "MIT",
2824
+ "engines": {
2825
+ "node": ">=12"
2826
+ },
2827
+ "funding": {
2828
+ "type": "github",
2829
+ "url": "https://github.com/sponsors/tannerlinsley"
2830
+ }
2831
+ },
2832
  "node_modules/@tanstack/virtual-core": {
2833
  "version": "3.13.21",
2834
  "resolved": "https://registry.npmjs.org/@tanstack/virtual-core/-/virtual-core-3.13.21.tgz",
 
2839
  "url": "https://github.com/sponsors/tannerlinsley"
2840
  }
2841
  },
2842
+ "node_modules/@tanstack/vue-query": {
2843
+ "version": "5.92.9",
2844
+ "resolved": "https://registry.npmjs.org/@tanstack/vue-query/-/vue-query-5.92.9.tgz",
2845
+ "integrity": "sha512-jjAZcqKveyX0C4w/6zUqbnqk/XzuxNWaFsWjGTJWULVFizUNeLGME2gf9vVSDclIyiBhR13oZJPPs6fJgfpIJQ==",
2846
+ "license": "MIT",
2847
+ "dependencies": {
2848
+ "@tanstack/match-sorter-utils": "^8.19.4",
2849
+ "@tanstack/query-core": "5.90.20",
2850
+ "@vue/devtools-api": "^6.6.3",
2851
+ "vue-demi": "^0.14.10"
2852
+ },
2853
+ "funding": {
2854
+ "type": "github",
2855
+ "url": "https://github.com/sponsors/tannerlinsley"
2856
+ },
2857
+ "peerDependencies": {
2858
+ "@vue/composition-api": "^1.1.2",
2859
+ "vue": "^2.6.0 || ^3.3.0"
2860
+ },
2861
+ "peerDependenciesMeta": {
2862
+ "@vue/composition-api": {
2863
+ "optional": true
2864
+ }
2865
+ }
2866
+ },
2867
+ "node_modules/@tanstack/vue-query/node_modules/@vue/devtools-api": {
2868
+ "version": "6.6.4",
2869
+ "resolved": "https://registry.npmjs.org/@vue/devtools-api/-/devtools-api-6.6.4.tgz",
2870
+ "integrity": "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g==",
2871
+ "license": "MIT"
2872
+ },
2873
+ "node_modules/@tanstack/vue-query/node_modules/vue-demi": {
2874
+ "version": "0.14.10",
2875
+ "resolved": "https://registry.npmjs.org/vue-demi/-/vue-demi-0.14.10.tgz",
2876
+ "integrity": "sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg==",
2877
+ "hasInstallScript": true,
2878
+ "license": "MIT",
2879
+ "bin": {
2880
+ "vue-demi-fix": "bin/vue-demi-fix.js",
2881
+ "vue-demi-switch": "bin/vue-demi-switch.js"
2882
+ },
2883
+ "engines": {
2884
+ "node": ">=12"
2885
+ },
2886
+ "funding": {
2887
+ "url": "https://github.com/sponsors/antfu"
2888
+ },
2889
+ "peerDependencies": {
2890
+ "@vue/composition-api": "^1.0.0-rc.1",
2891
+ "vue": "^3.0.0-0 || ^2.6.0"
2892
+ },
2893
+ "peerDependenciesMeta": {
2894
+ "@vue/composition-api": {
2895
+ "optional": true
2896
+ }
2897
+ }
2898
+ },
2899
+ "node_modules/@tanstack/vue-table": {
2900
+ "version": "8.21.3",
2901
+ "resolved": "https://registry.npmjs.org/@tanstack/vue-table/-/vue-table-8.21.3.tgz",
2902
+ "integrity": "sha512-rusRyd77c5tDPloPskctMyPLFEQUeBzxdQ+2Eow4F7gDPlPOB1UnnhzfpdvqZ8ZyX2rRNGmqNnQWm87OI2OQPw==",
2903
+ "license": "MIT",
2904
+ "dependencies": {
2905
+ "@tanstack/table-core": "8.21.3"
2906
+ },
2907
+ "engines": {
2908
+ "node": ">=12"
2909
+ },
2910
+ "funding": {
2911
+ "type": "github",
2912
+ "url": "https://github.com/sponsors/tannerlinsley"
2913
+ },
2914
+ "peerDependencies": {
2915
+ "vue": ">=3.2"
2916
+ }
2917
+ },
2918
  "node_modules/@tanstack/vue-virtual": {
2919
  "version": "3.13.21",
2920
  "resolved": "https://registry.npmjs.org/@tanstack/vue-virtual/-/vue-virtual-3.13.21.tgz",
 
6646
  "vue": ">= 3.4.0"
6647
  }
6648
  },
6649
+ "node_modules/remove-accents": {
6650
+ "version": "0.5.0",
6651
+ "resolved": "https://registry.npmjs.org/remove-accents/-/remove-accents-0.5.0.tgz",
6652
+ "integrity": "sha512-8g3/Otx1eJaVD12e31UbJj1YzdtVvzH85HV7t+9MJYk/u3XmkOUJ5Ys9wQrf9PCPK8+xn4ymzqYCiZl6QWKn+A==",
6653
+ "license": "MIT"
6654
+ },
6655
  "node_modules/require-from-string": {
6656
  "version": "2.0.2",
6657
  "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz",
web/package.json CHANGED
@@ -18,6 +18,9 @@
18
  },
19
  "dependencies": {
20
  "@tailwindcss/vite": "^4.2.1",
 
 
 
21
  "class-variance-authority": "^0.7.1",
22
  "clsx": "^2.1.1",
23
  "lucide-vue-next": "^0.577.0",
 
18
  },
19
  "dependencies": {
20
  "@tailwindcss/vite": "^4.2.1",
21
+ "@tanstack/vue-query": "^5.92.9",
22
+ "@tanstack/vue-table": "^8.21.3",
23
+ "@vueuse/core": "^14.2.1",
24
  "class-variance-authority": "^0.7.1",
25
  "clsx": "^2.1.1",
26
  "lucide-vue-next": "^0.577.0",
web/src/__tests__/lib/api.spec.ts CHANGED
@@ -11,15 +11,10 @@ vi.mock('@/stores/auth', () => ({
11
  useAuthStore: () => mockAuthStore,
12
  }))
13
 
14
- const mockRouter = {
15
- push: vi.fn(),
16
- }
17
-
18
- vi.mock('@/router', () => ({
19
- default: mockRouter,
20
- }))
21
 
22
- import { get, post, del } from '@/lib/api'
 
23
 
24
  function makeFetchResponse(status: number, body: unknown = {}) {
25
  return {
@@ -37,7 +32,7 @@ describe('api', () => {
37
  mockAuthStore.token = 'test-token'
38
  mockAuthStore.refresh = vi.fn()
39
  mockAuthStore.logout = vi.fn()
40
- mockRouter.push = vi.fn()
41
  })
42
 
43
  it('get adds Authorization header when token exists', async () => {
@@ -100,6 +95,67 @@ describe('api', () => {
100
 
101
  expect(mockAuthStore.refresh).toHaveBeenCalled()
102
  expect(mockAuthStore.logout).toHaveBeenCalled()
103
- expect(mockRouter.push).toHaveBeenCalledWith({ name: 'login' })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  })
105
  })
 
11
  useAuthStore: () => mockAuthStore,
12
  }))
13
 
14
+ import { get, post, del, setOnAuthFailure } from '@/lib/api'
 
 
 
 
 
 
15
 
16
+ const mockOnAuthFailure = vi.fn()
17
+ setOnAuthFailure(mockOnAuthFailure)
18
 
19
  function makeFetchResponse(status: number, body: unknown = {}) {
20
  return {
 
32
  mockAuthStore.token = 'test-token'
33
  mockAuthStore.refresh = vi.fn()
34
  mockAuthStore.logout = vi.fn()
35
+ mockOnAuthFailure.mockClear()
36
  })
37
 
38
  it('get adds Authorization header when token exists', async () => {
 
95
 
96
  expect(mockAuthStore.refresh).toHaveBeenCalled()
97
  expect(mockAuthStore.logout).toHaveBeenCalled()
98
+ expect(mockOnAuthFailure).toHaveBeenCalled()
99
+ })
100
+
101
+ it('non-401 error passes through without refresh', async () => {
102
+ const fetchMock = vi.fn().mockResolvedValue(makeFetchResponse(500, { error: 'server error' }))
103
+ vi.stubGlobal('fetch', fetchMock)
104
+
105
+ const res = await get('/api/broken')
106
+
107
+ expect(res.status).toBe(500)
108
+ expect(mockAuthStore.refresh).not.toHaveBeenCalled()
109
+ expect(mockAuthStore.logout).not.toHaveBeenCalled()
110
+ })
111
+
112
+ it('includes credentials in fetch calls', async () => {
113
+ const fetchMock = vi.fn().mockResolvedValue(makeFetchResponse(200))
114
+ vi.stubGlobal('fetch', fetchMock)
115
+
116
+ await get('/api/test')
117
+
118
+ const [, options] = fetchMock.mock.calls[0]
119
+ expect(options.credentials).toBe('include')
120
+ })
121
+
122
+ it('does not set Authorization header when token is null', async () => {
123
+ mockAuthStore.token = null as unknown as string
124
+ const fetchMock = vi.fn().mockResolvedValue(makeFetchResponse(200))
125
+ vi.stubGlobal('fetch', fetchMock)
126
+
127
+ await get('/api/public')
128
+
129
+ const [, options] = fetchMock.mock.calls[0]
130
+ expect(options.headers.has('Authorization')).toBe(false)
131
+ })
132
+
133
+ it('network error propagates', async () => {
134
+ const fetchMock = vi.fn().mockRejectedValue(new TypeError('Failed to fetch'))
135
+ vi.stubGlobal('fetch', fetchMock)
136
+
137
+ await expect(get('/api/test')).rejects.toThrow('Failed to fetch')
138
+ })
139
+
140
+ it('401 without token does not attempt refresh', async () => {
141
+ mockAuthStore.token = null as unknown as string
142
+ const fetchMock = vi.fn().mockResolvedValue(makeFetchResponse(401))
143
+ vi.stubGlobal('fetch', fetchMock)
144
+
145
+ const res = await get('/api/protected')
146
+
147
+ expect(res.status).toBe(401)
148
+ expect(mockAuthStore.refresh).not.toHaveBeenCalled()
149
+ })
150
+
151
+ it('post without body does not set Content-Type', async () => {
152
+ const fetchMock = vi.fn().mockResolvedValue(makeFetchResponse(200))
153
+ vi.stubGlobal('fetch', fetchMock)
154
+
155
+ await post('/api/action')
156
+
157
+ const [, options] = fetchMock.mock.calls[0]
158
+ expect(options.headers.has('Content-Type')).toBe(false)
159
+ expect(options.body).toBeUndefined()
160
  })
161
  })
web/src/__tests__/router/index.spec.ts CHANGED
@@ -10,15 +10,18 @@ function makeRouter() {
10
  return createRouter({
11
  history: createWebHistory(),
12
  routes: [
13
- { path: '/', redirect: '/keys' },
14
- { path: '/login', name: 'login', component: { template: '<div>Login</div>' } },
15
- { path: '/setup', name: 'setup', component: { template: '<div>Setup</div>' } },
16
  {
17
- path: '/keys',
18
- name: 'keys',
19
- component: { template: '<div>Keys</div>' },
20
  meta: { requiresAuth: true },
 
 
 
 
 
21
  },
 
 
22
  ],
23
  })
24
  }
@@ -28,25 +31,25 @@ describe('router', () => {
28
  setActivePinia(createPinia())
29
  })
30
 
31
- it('unauthenticated user visiting /keys gets redirected to /login', async () => {
32
  const router = makeRouter()
33
  const auth = useAuthStore()
34
 
35
  vi.spyOn(auth, 'checkSetupRequired').mockResolvedValue(false)
36
 
37
  router.beforeEach(async (to) => {
38
- if (to.meta.requiresAuth && !auth.isAuthenticated) {
39
  return { name: 'login' }
40
  }
41
  })
42
 
43
- await router.push('/keys')
44
  await router.isReady()
45
 
46
  expect(router.currentRoute.value.name).toBe('login')
47
  })
48
 
49
- it('authenticated user visiting /login gets redirected to /keys', async () => {
50
  const router = makeRouter()
51
  const auth = useAuthStore()
52
  auth.token = 'valid-token'
@@ -55,13 +58,13 @@ describe('router', () => {
55
 
56
  router.beforeEach(async (to) => {
57
  if ((to.name === 'login' || to.name === 'setup') && auth.isAuthenticated) {
58
- return { name: 'keys' }
59
  }
60
  })
61
 
62
  await router.push('/login')
63
  await router.isReady()
64
 
65
- expect(router.currentRoute.value.name).toBe('keys')
66
  })
67
  })
 
10
  return createRouter({
11
  history: createWebHistory(),
12
  routes: [
 
 
 
13
  {
14
+ path: '/',
15
+ component: { template: '<router-view />' },
 
16
  meta: { requiresAuth: true },
17
+ children: [
18
+ { path: '', name: 'dashboard', component: { template: '<div>Dashboard</div>' } },
19
+ { path: 'posters', name: 'posters', component: { template: '<div>Posters</div>' } },
20
+ { path: 'keys', name: 'keys', component: { template: '<div>Keys</div>' } },
21
+ ],
22
  },
23
+ { path: '/login', name: 'login', component: { template: '<div>Login</div>' } },
24
+ { path: '/setup', name: 'setup', component: { template: '<div>Setup</div>' } },
25
  ],
26
  })
27
  }
 
31
  setActivePinia(createPinia())
32
  })
33
 
34
+ it('unauthenticated user visiting / gets redirected to /login', async () => {
35
  const router = makeRouter()
36
  const auth = useAuthStore()
37
 
38
  vi.spyOn(auth, 'checkSetupRequired').mockResolvedValue(false)
39
 
40
  router.beforeEach(async (to) => {
41
+ if (to.matched.some((r) => r.meta.requiresAuth) && !auth.isAuthenticated) {
42
  return { name: 'login' }
43
  }
44
  })
45
 
46
+ await router.push('/')
47
  await router.isReady()
48
 
49
  expect(router.currentRoute.value.name).toBe('login')
50
  })
51
 
52
+ it('authenticated user visiting /login gets redirected to dashboard', async () => {
53
  const router = makeRouter()
54
  const auth = useAuthStore()
55
  auth.token = 'valid-token'
 
58
 
59
  router.beforeEach(async (to) => {
60
  if ((to.name === 'login' || to.name === 'setup') && auth.isAuthenticated) {
61
+ return { name: 'dashboard' }
62
  }
63
  })
64
 
65
  await router.push('/login')
66
  await router.isReady()
67
 
68
+ expect(router.currentRoute.value.name).toBe('dashboard')
69
  })
70
  })
web/src/__tests__/stores/auth.spec.ts CHANGED
@@ -130,4 +130,88 @@ describe('auth store', () => {
130
  expect(second).toBe(true)
131
  expect(fetchMock).toHaveBeenCalledTimes(1)
132
  })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
  })
 
130
  expect(second).toBe(true)
131
  expect(fetchMock).toHaveBeenCalledTimes(1)
132
  })
133
+
134
+ it('refresh returns false on failure', async () => {
135
+ const fetchMock = mockFetchSuccess({}, false)
136
+ vi.stubGlobal('fetch', fetchMock)
137
+ const auth = useAuthStore()
138
+
139
+ const result = await auth.refresh()
140
+
141
+ expect(result).toBe(false)
142
+ expect(auth.token).toBeNull()
143
+ })
144
+
145
+ it('setup returns false on failure', async () => {
146
+ const fetchMock = mockFetchSuccess({}, false)
147
+ vi.stubGlobal('fetch', fetchMock)
148
+ const auth = useAuthStore()
149
+
150
+ const result = await auth.setup('admin', 'password123')
151
+
152
+ expect(result).toBe(false)
153
+ expect(auth.token).toBeNull()
154
+ })
155
+
156
+ it('checkSetupRequired throws on network error', async () => {
157
+ const fetchMock = vi.fn().mockResolvedValue({
158
+ ok: false,
159
+ status: 500,
160
+ json: () => Promise.resolve({}),
161
+ })
162
+ vi.stubGlobal('fetch', fetchMock)
163
+ const auth = useAuthStore()
164
+
165
+ await expect(auth.checkSetupRequired()).rejects.toThrow('status check failed')
166
+ })
167
+
168
+ it('login sends credentials include', async () => {
169
+ const fetchMock = mockFetchSuccess({ token: 'tok' })
170
+ vi.stubGlobal('fetch', fetchMock)
171
+ const auth = useAuthStore()
172
+
173
+ await auth.login('user', 'pass')
174
+
175
+ const [, options] = fetchMock.mock.calls[0]
176
+ expect(options.credentials).toBe('include')
177
+ })
178
+
179
+ it('setup sends credentials include', async () => {
180
+ const fetchMock = mockFetchSuccess({ token: 'tok' })
181
+ vi.stubGlobal('fetch', fetchMock)
182
+ const auth = useAuthStore()
183
+
184
+ await auth.setup('user', 'password123')
185
+
186
+ const [, options] = fetchMock.mock.calls[0]
187
+ expect(options.credentials).toBe('include')
188
+ })
189
+
190
+ it('refresh sends credentials include', async () => {
191
+ const fetchMock = mockFetchSuccess({ token: 'tok' })
192
+ vi.stubGlobal('fetch', fetchMock)
193
+ const auth = useAuthStore()
194
+
195
+ await auth.refresh()
196
+
197
+ const [, options] = fetchMock.mock.calls[0]
198
+ expect(options.credentials).toBe('include')
199
+ })
200
+
201
+ it('setup failure does not change setupRequired', async () => {
202
+ const fetchMock = mockFetchSuccess({}, false)
203
+ vi.stubGlobal('fetch', fetchMock)
204
+ const auth = useAuthStore()
205
+
206
+ await auth.setup('admin', 'password123')
207
+
208
+ // setupRequired should still be null (not changed on failure)
209
+ expect(auth.setupRequired).toBeNull()
210
+ })
211
+
212
+ it('initializes token from localStorage', () => {
213
+ localStorageMock['token'] = 'persisted-token'
214
+ const auth = useAuthStore()
215
+ expect(auth.token).toBe('persisted-token')
216
+ })
217
  })
web/src/__tests__/views/ApiKeysView.spec.ts CHANGED
@@ -1,34 +1,17 @@
1
  import { describe, it, expect, vi, beforeEach } from 'vitest'
2
  import { mount, flushPromises } from '@vue/test-utils'
3
  import { createPinia, setActivePinia } from 'pinia'
 
4
  import ApiKeysView from '@/views/ApiKeysView.vue'
5
 
6
- const mockRouter = {
7
- push: vi.fn(),
8
- }
9
-
10
- const mockAuthStore = {
11
- logout: vi.fn(),
12
- }
13
-
14
- const mockApi = {
15
- get: vi.fn(),
16
- post: vi.fn(),
17
- del: vi.fn(),
18
- }
19
-
20
- vi.mock('vue-router', () => ({
21
- useRouter: () => mockRouter,
22
- }))
23
-
24
- vi.mock('@/stores/auth', () => ({
25
- useAuthStore: () => mockAuthStore,
26
  }))
27
 
28
  vi.mock('@/lib/api', () => ({
29
- get: (...args: unknown[]) => mockApi.get(...args),
30
- post: (...args: unknown[]) => mockApi.post(...args),
31
- del: (...args: unknown[]) => mockApi.del(...args),
32
  }))
33
 
34
  const sampleKeys = [
@@ -49,14 +32,21 @@ const sampleKeys = [
49
  ]
50
 
51
  function mountView() {
 
 
 
52
  return mount(ApiKeysView, {
53
  global: {
54
- plugins: [createPinia()],
55
  stubs: {
56
  Button: {
57
  template: '<button @click="$emit(\'click\')"><slot /></button>',
58
  props: ['disabled', 'variant', 'size'],
59
  },
 
 
 
 
60
  },
61
  },
62
  })
@@ -66,14 +56,14 @@ describe('ApiKeysView', () => {
66
  beforeEach(() => {
67
  setActivePinia(createPinia())
68
  vi.clearAllMocks()
69
- mockApi.get.mockResolvedValue({
70
  ok: true,
71
  json: () => Promise.resolve([]),
72
  })
73
  })
74
 
75
  it('renders key list from mocked API response', async () => {
76
- mockApi.get.mockResolvedValue({
77
  ok: true,
78
  json: () => Promise.resolve(sampleKeys),
79
  })
@@ -88,7 +78,7 @@ describe('ApiKeysView', () => {
88
  })
89
 
90
  it('shows "No API keys yet." when empty', async () => {
91
- mockApi.get.mockResolvedValue({
92
  ok: true,
93
  json: () => Promise.resolve([]),
94
  })
@@ -99,17 +89,27 @@ describe('ApiKeysView', () => {
99
  expect(wrapper.text()).toContain('No API keys yet.')
100
  })
101
 
102
- it('logout button calls auth.logout', async () => {
 
 
 
 
 
103
  const wrapper = mountView()
104
  await flushPromises()
105
 
106
- const buttons = wrapper.findAll('button')
107
- const logoutButton = buttons.find((b) => b.text().includes('Sign out'))
108
- expect(logoutButton).toBeDefined()
 
 
109
 
110
- await logoutButton!.trigger('click')
 
 
 
 
111
 
112
- expect(mockAuthStore.logout).toHaveBeenCalled()
113
- expect(mockRouter.push).toHaveBeenCalledWith('/login')
114
  })
115
  })
 
1
  import { describe, it, expect, vi, beforeEach } from 'vitest'
2
  import { mount, flushPromises } from '@vue/test-utils'
3
  import { createPinia, setActivePinia } from 'pinia'
4
+ import { QueryClient, VueQueryPlugin } from '@tanstack/vue-query'
5
  import ApiKeysView from '@/views/ApiKeysView.vue'
6
 
7
+ const mockKeysApi = vi.hoisted(() => ({
8
+ list: vi.fn(),
9
+ create: vi.fn(),
10
+ delete: vi.fn(),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
  }))
12
 
13
  vi.mock('@/lib/api', () => ({
14
+ keysApi: mockKeysApi,
 
 
15
  }))
16
 
17
  const sampleKeys = [
 
32
  ]
33
 
34
  function mountView() {
35
+ const queryClient = new QueryClient({
36
+ defaultOptions: { queries: { retry: false } },
37
+ })
38
  return mount(ApiKeysView, {
39
  global: {
40
+ plugins: [createPinia(), [VueQueryPlugin, { queryClient }]],
41
  stubs: {
42
  Button: {
43
  template: '<button @click="$emit(\'click\')"><slot /></button>',
44
  props: ['disabled', 'variant', 'size'],
45
  },
46
+ Input: {
47
+ template: '<input :value="modelValue" @input="$emit(\'update:modelValue\', $event.target.value)" />',
48
+ props: ['modelValue', 'type', 'placeholder', 'required'],
49
+ },
50
  },
51
  },
52
  })
 
56
  beforeEach(() => {
57
  setActivePinia(createPinia())
58
  vi.clearAllMocks()
59
+ mockKeysApi.list.mockResolvedValue({
60
  ok: true,
61
  json: () => Promise.resolve([]),
62
  })
63
  })
64
 
65
  it('renders key list from mocked API response', async () => {
66
+ mockKeysApi.list.mockResolvedValue({
67
  ok: true,
68
  json: () => Promise.resolve(sampleKeys),
69
  })
 
78
  })
79
 
80
  it('shows "No API keys yet." when empty', async () => {
81
+ mockKeysApi.list.mockResolvedValue({
82
  ok: true,
83
  json: () => Promise.resolve([]),
84
  })
 
89
  expect(wrapper.text()).toContain('No API keys yet.')
90
  })
91
 
92
+ it('has a refresh button that triggers refetch', async () => {
93
+ mockKeysApi.list.mockResolvedValue({
94
+ ok: true,
95
+ json: () => Promise.resolve(sampleKeys),
96
+ })
97
+
98
  const wrapper = mountView()
99
  await flushPromises()
100
 
101
+ mockKeysApi.list.mockClear()
102
+ mockKeysApi.list.mockResolvedValue({
103
+ ok: true,
104
+ json: () => Promise.resolve([sampleKeys[0]]),
105
+ })
106
 
107
+ const refreshButton = wrapper.findAll('button').find((b) => b.text().includes('Refresh'))
108
+ expect(refreshButton).toBeDefined()
109
+
110
+ await refreshButton!.trigger('click')
111
+ await flushPromises()
112
 
113
+ expect(mockKeysApi.list).toHaveBeenCalled()
 
114
  })
115
  })
web/src/__tests__/views/DashboardView.spec.ts ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest'
2
+ import { mount, flushPromises } from '@vue/test-utils'
3
+ import { createPinia, setActivePinia } from 'pinia'
4
+ import { QueryClient, VueQueryPlugin } from '@tanstack/vue-query'
5
+ import DashboardView from '@/views/DashboardView.vue'
6
+
7
+ const mockAdminApi = vi.hoisted(() => ({
8
+ getStats: vi.fn(),
9
+ }))
10
+
11
+ vi.mock('@/lib/api', () => ({
12
+ adminApi: mockAdminApi,
13
+ }))
14
+
15
+ const sampleStats = {
16
+ total_posters: 42,
17
+ total_api_keys: 3,
18
+ mem_cache_entries: 100,
19
+ id_cache_entries: 50,
20
+ ratings_cache_entries: 25,
21
+ poster_mem_cache_mb: 128,
22
+ }
23
+
24
+ function mountView() {
25
+ const queryClient = new QueryClient({
26
+ defaultOptions: { queries: { retry: false } },
27
+ })
28
+ return mount(DashboardView, {
29
+ global: {
30
+ plugins: [createPinia(), [VueQueryPlugin, { queryClient }]],
31
+ stubs: {
32
+ Button: {
33
+ template: '<button @click="$emit(\'click\')" :disabled="disabled"><slot /></button>',
34
+ props: ['disabled', 'variant', 'size'],
35
+ },
36
+ Card: { template: '<div><slot /></div>' },
37
+ CardHeader: { template: '<div><slot /></div>' },
38
+ CardTitle: { template: '<div><slot /></div>' },
39
+ CardContent: { template: '<div><slot /></div>' },
40
+ Skeleton: { template: '<div data-testid="skeleton" />' },
41
+ RefreshCw: { template: '<span />' },
42
+ },
43
+ },
44
+ })
45
+ }
46
+
47
+ describe('DashboardView', () => {
48
+ beforeEach(() => {
49
+ setActivePinia(createPinia())
50
+ vi.clearAllMocks()
51
+ })
52
+
53
+ it('shows skeletons while loading', () => {
54
+ mockAdminApi.getStats.mockReturnValue(new Promise(() => {})) // never resolves
55
+ const wrapper = mountView()
56
+ expect(wrapper.findAll('[data-testid="skeleton"]').length).toBeGreaterThan(0)
57
+ })
58
+
59
+ it('renders stats from API response', async () => {
60
+ mockAdminApi.getStats.mockResolvedValue({
61
+ ok: true,
62
+ json: () => Promise.resolve(sampleStats),
63
+ })
64
+
65
+ const wrapper = mountView()
66
+ await flushPromises()
67
+
68
+ expect(wrapper.text()).toContain('42')
69
+ expect(wrapper.text()).toContain('3')
70
+ expect(wrapper.text()).toContain('100')
71
+ expect(wrapper.text()).toContain('128')
72
+ })
73
+
74
+ it('has a refresh button', async () => {
75
+ mockAdminApi.getStats.mockResolvedValue({
76
+ ok: true,
77
+ json: () => Promise.resolve(sampleStats),
78
+ })
79
+
80
+ const wrapper = mountView()
81
+ await flushPromises()
82
+
83
+ const refreshButton = wrapper.findAll('button').find((b) => b.text().includes('Refresh'))
84
+ expect(refreshButton).toBeDefined()
85
+ })
86
+
87
+ it('refresh button triggers refetch', async () => {
88
+ mockAdminApi.getStats.mockResolvedValue({
89
+ ok: true,
90
+ json: () => Promise.resolve(sampleStats),
91
+ })
92
+
93
+ const wrapper = mountView()
94
+ await flushPromises()
95
+
96
+ mockAdminApi.getStats.mockClear()
97
+ mockAdminApi.getStats.mockResolvedValue({
98
+ ok: true,
99
+ json: () => Promise.resolve({ ...sampleStats, total_posters: 99 }),
100
+ })
101
+
102
+ const refreshButton = wrapper.findAll('button').find((b) => b.text().includes('Refresh'))
103
+ await refreshButton!.trigger('click')
104
+ await flushPromises()
105
+
106
+ expect(mockAdminApi.getStats).toHaveBeenCalled()
107
+ expect(wrapper.text()).toContain('99')
108
+ })
109
+ })
web/src/__tests__/views/LoginView.spec.ts CHANGED
@@ -77,6 +77,6 @@ describe('LoginView', () => {
77
  await flushPromises()
78
 
79
  expect(mockAuthStore.login).toHaveBeenCalledWith('admin', 'secret')
80
- expect(mockRouter.push).toHaveBeenCalledWith('/keys')
81
  })
82
  })
 
77
  await flushPromises()
78
 
79
  expect(mockAuthStore.login).toHaveBeenCalledWith('admin', 'secret')
80
+ expect(mockRouter.push).toHaveBeenCalledWith('/')
81
  })
82
  })
web/src/__tests__/views/PostersView.spec.ts ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest'
2
+ import { mount, flushPromises } from '@vue/test-utils'
3
+ import { createPinia, setActivePinia } from 'pinia'
4
+ import { QueryClient, VueQueryPlugin } from '@tanstack/vue-query'
5
+ import { createRouter, createMemoryHistory } from 'vue-router'
6
+ import PostersView from '@/views/PostersView.vue'
7
+
8
+ const mockAdminApi = vi.hoisted(() => ({
9
+ getPosters: vi.fn(),
10
+ getPosterImage: vi.fn(),
11
+ }))
12
+
13
+ vi.mock('@/lib/api', () => ({
14
+ adminApi: mockAdminApi,
15
+ }))
16
+
17
+ const sampleResponse = {
18
+ items: [
19
+ {
20
+ cache_key: 'imdb/tt0111161',
21
+ release_date: '1994-09-23',
22
+ created_at: 1710000000,
23
+ updated_at: 1710100000,
24
+ },
25
+ {
26
+ cache_key: 'tmdb/550',
27
+ release_date: '1999-10-15',
28
+ created_at: 1710000000,
29
+ updated_at: 1710100000,
30
+ },
31
+ ],
32
+ total: 2,
33
+ page: 1,
34
+ page_size: 50,
35
+ }
36
+
37
+ function mountView() {
38
+ const queryClient = new QueryClient({
39
+ defaultOptions: { queries: { retry: false } },
40
+ })
41
+ const router = createRouter({
42
+ history: createMemoryHistory(),
43
+ routes: [{ path: '/', component: PostersView }],
44
+ })
45
+ return mount(PostersView, {
46
+ global: {
47
+ plugins: [createPinia(), router, [VueQueryPlugin, { queryClient }]],
48
+ stubs: {
49
+ Button: {
50
+ template: '<button @click="$emit(\'click\')" :disabled="disabled"><slot /></button>',
51
+ props: ['disabled', 'variant', 'size'],
52
+ },
53
+ Skeleton: { template: '<div data-testid="skeleton" />' },
54
+ Table: { template: '<table><slot /></table>' },
55
+ TableHeader: { template: '<thead><slot /></thead>' },
56
+ TableBody: { template: '<tbody><slot /></tbody>' },
57
+ TableRow: { template: '<tr><slot /></tr>' },
58
+ TableHead: { template: '<th><slot /></th>' },
59
+ TableCell: { template: '<td><slot /></td>' },
60
+ RefreshCw: { template: '<span />' },
61
+ },
62
+ },
63
+ })
64
+ }
65
+
66
+ describe('PostersView', () => {
67
+ beforeEach(() => {
68
+ setActivePinia(createPinia())
69
+ vi.clearAllMocks()
70
+ })
71
+
72
+ it('shows skeletons while loading', () => {
73
+ mockAdminApi.getPosters.mockReturnValue(new Promise(() => {}))
74
+ const wrapper = mountView()
75
+ expect(wrapper.findAll('[data-testid="skeleton"]').length).toBeGreaterThan(0)
76
+ })
77
+
78
+ it('renders poster list with parsed cache keys', async () => {
79
+ mockAdminApi.getPosters.mockResolvedValue({
80
+ ok: true,
81
+ json: () => Promise.resolve(sampleResponse),
82
+ })
83
+
84
+ const wrapper = mountView()
85
+ await flushPromises()
86
+
87
+ expect(wrapper.text()).toContain('imdb')
88
+ expect(wrapper.text()).toContain('tt0111161')
89
+ expect(wrapper.text()).toContain('tmdb')
90
+ expect(wrapper.text()).toContain('550')
91
+ expect(wrapper.text()).toContain('1994-09-23')
92
+ })
93
+
94
+ it('shows empty state when no posters', async () => {
95
+ mockAdminApi.getPosters.mockResolvedValue({
96
+ ok: true,
97
+ json: () => Promise.resolve({ items: [], total: 0, page: 1, page_size: 50 }),
98
+ })
99
+
100
+ const wrapper = mountView()
101
+ await flushPromises()
102
+
103
+ expect(wrapper.text()).toContain('No posters cached yet.')
104
+ })
105
+
106
+ it('shows total count and pagination info', async () => {
107
+ mockAdminApi.getPosters.mockResolvedValue({
108
+ ok: true,
109
+ json: () => Promise.resolve(sampleResponse),
110
+ })
111
+
112
+ const wrapper = mountView()
113
+ await flushPromises()
114
+
115
+ expect(wrapper.text()).toContain('2 posters total')
116
+ expect(wrapper.text()).toContain('Page 1 of 1')
117
+ })
118
+
119
+ it('has a refresh button', async () => {
120
+ mockAdminApi.getPosters.mockResolvedValue({
121
+ ok: true,
122
+ json: () => Promise.resolve(sampleResponse),
123
+ })
124
+
125
+ const wrapper = mountView()
126
+ await flushPromises()
127
+
128
+ const refreshButton = wrapper.findAll('button').find((b) => b.text().includes('Refresh'))
129
+ expect(refreshButton).toBeDefined()
130
+ })
131
+
132
+ it('refresh button triggers refetch', async () => {
133
+ mockAdminApi.getPosters.mockResolvedValue({
134
+ ok: true,
135
+ json: () => Promise.resolve(sampleResponse),
136
+ })
137
+
138
+ const wrapper = mountView()
139
+ await flushPromises()
140
+
141
+ mockAdminApi.getPosters.mockClear()
142
+ mockAdminApi.getPosters.mockResolvedValue({
143
+ ok: true,
144
+ json: () => Promise.resolve({ ...sampleResponse, total: 10 }),
145
+ })
146
+
147
+ const refreshButton = wrapper.findAll('button').find((b) => b.text().includes('Refresh'))
148
+ await refreshButton!.trigger('click')
149
+ await flushPromises()
150
+
151
+ expect(mockAdminApi.getPosters).toHaveBeenCalled()
152
+ expect(wrapper.text()).toContain('10 posters total')
153
+ })
154
+ })
web/src/__tests__/views/SetupView.spec.ts CHANGED
@@ -86,6 +86,6 @@ describe('SetupView', () => {
86
  await flushPromises()
87
 
88
  expect(mockAuthStore.setup).toHaveBeenCalledWith('admin', 'password123')
89
- expect(mockRouter.push).toHaveBeenCalledWith('/keys')
90
  })
91
  })
 
86
  await flushPromises()
87
 
88
  expect(mockAuthStore.setup).toHaveBeenCalledWith('admin', 'password123')
89
+ expect(mockRouter.push).toHaveBeenCalledWith('/')
90
  })
91
  })
web/src/components/AppSidebar.vue ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import { useRoute, useRouter } from 'vue-router'
3
+ import { useAuthStore } from '@/stores/auth'
4
+ import { LayoutDashboard, Image, KeyRound, LogOut } from 'lucide-vue-next'
5
+ import {
6
+ Sidebar,
7
+ SidebarContent,
8
+ SidebarFooter,
9
+ SidebarGroup,
10
+ SidebarHeader,
11
+ SidebarMenu,
12
+ SidebarMenuButton,
13
+ SidebarMenuItem,
14
+ SidebarRail,
15
+ useSidebar,
16
+ } from '@/components/ui/sidebar'
17
+ import { Button } from '@/components/ui/button'
18
+
19
+ const route = useRoute()
20
+ const router = useRouter()
21
+ const auth = useAuthStore()
22
+ const { state, isMobile, setOpenMobile } = useSidebar()
23
+
24
+ const items = [
25
+ { title: 'Dashboard', icon: LayoutDashboard, to: '/' },
26
+ { title: 'Posters', icon: Image, to: '/posters' },
27
+ { title: 'API Keys', icon: KeyRound, to: '/keys' },
28
+ ]
29
+
30
+ function isActive(path: string) {
31
+ return route.path === path
32
+ }
33
+
34
+ function onNavigate() {
35
+ if (isMobile.value) setOpenMobile(false)
36
+ }
37
+
38
+ function handleLogout() {
39
+ if (isMobile.value) setOpenMobile(false)
40
+ auth.logout()
41
+ router.push('/login')
42
+ }
43
+ </script>
44
+
45
+ <template>
46
+ <Sidebar variant="inset" collapsible="icon">
47
+ <SidebarHeader>
48
+ <router-link to="/" class="flex items-center justify-center py-1 group-data-[state=expanded]/sidebar-wrapper:justify-start hover:opacity-80 transition-opacity" @click="onNavigate">
49
+ <span class="font-bold text-lg whitespace-nowrap">{{ state === 'collapsed' ? 'OPDB' : 'OpenPosterDB' }}</span>
50
+ </router-link>
51
+ </SidebarHeader>
52
+ <SidebarContent>
53
+ <SidebarGroup>
54
+ <SidebarMenu>
55
+ <SidebarMenuItem v-for="item in items" :key="item.title">
56
+ <SidebarMenuButton
57
+ as-child
58
+ :is-active="isActive(item.to)"
59
+ :tooltip="item.title"
60
+ >
61
+ <router-link :to="item.to" @click="onNavigate">
62
+ <component :is="item.icon" />
63
+ <span>{{ item.title }}</span>
64
+ </router-link>
65
+ </SidebarMenuButton>
66
+ </SidebarMenuItem>
67
+ </SidebarMenu>
68
+ </SidebarGroup>
69
+ </SidebarContent>
70
+ <SidebarFooter>
71
+ <SidebarMenu>
72
+ <SidebarMenuItem>
73
+ <SidebarMenuButton tooltip="Sign out" @click="handleLogout">
74
+ <LogOut />
75
+ <span>Sign out</span>
76
+ </SidebarMenuButton>
77
+ </SidebarMenuItem>
78
+ </SidebarMenu>
79
+ </SidebarFooter>
80
+ <SidebarRail />
81
+ </Sidebar>
82
+ </template>
web/src/components/RefreshButton.vue ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import { ref, watch } from 'vue'
3
+ import { RefreshCw, Check } from 'lucide-vue-next'
4
+ import { Button } from '@/components/ui/button'
5
+
6
+ const props = defineProps<{
7
+ fetching: boolean
8
+ }>()
9
+
10
+ const emit = defineEmits<{
11
+ refresh: []
12
+ }>()
13
+
14
+ const showCheck = ref(false)
15
+ let timeout: ReturnType<typeof setTimeout> | null = null
16
+
17
+ watch(() => props.fetching, (now, was) => {
18
+ if (was && !now) {
19
+ showCheck.value = true
20
+ if (timeout) clearTimeout(timeout)
21
+ timeout = setTimeout(() => {
22
+ showCheck.value = false
23
+ }, 1500)
24
+ }
25
+ })
26
+ </script>
27
+
28
+ <template>
29
+ <Button variant="outline" size="sm" :disabled="fetching" @click="emit('refresh')">
30
+ <span class="relative size-4">
31
+ <Transition
32
+ enter-active-class="transition duration-200 ease-out"
33
+ enter-from-class="opacity-0 scale-50"
34
+ enter-to-class="opacity-100 scale-100"
35
+ leave-active-class="transition duration-150 ease-in"
36
+ leave-from-class="opacity-100 scale-100"
37
+ leave-to-class="opacity-0 scale-50"
38
+ >
39
+ <Check v-if="showCheck" class="absolute inset-0 size-4 text-green-500" />
40
+ <RefreshCw v-else class="absolute inset-0 size-4" :class="{ 'animate-spin': fetching }" />
41
+ </Transition>
42
+ </span>
43
+ Refresh
44
+ </Button>
45
+ </template>
web/src/components/ui/badge/Badge.vue ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import type { PrimitiveProps } from "reka-ui"
3
+ import type { HTMLAttributes } from "vue"
4
+ import type { BadgeVariants } from "."
5
+ import { reactiveOmit } from "@vueuse/core"
6
+ import { Primitive } from "reka-ui"
7
+ import { cn } from "@/lib/utils"
8
+ import { badgeVariants } from "."
9
+
10
+ const props = defineProps<PrimitiveProps & {
11
+ variant?: BadgeVariants["variant"]
12
+ class?: HTMLAttributes["class"]
13
+ }>()
14
+
15
+ const delegatedProps = reactiveOmit(props, "class")
16
+ </script>
17
+
18
+ <template>
19
+ <Primitive
20
+ data-slot="badge"
21
+ :class="cn(badgeVariants({ variant }), props.class)"
22
+ v-bind="delegatedProps"
23
+ >
24
+ <slot />
25
+ </Primitive>
26
+ </template>
web/src/components/ui/badge/index.ts ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import type { VariantProps } from "class-variance-authority"
2
+ import { cva } from "class-variance-authority"
3
+
4
+ export { default as Badge } from "./Badge.vue"
5
+
6
+ export const badgeVariants = cva(
7
+ "inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",
8
+ {
9
+ variants: {
10
+ variant: {
11
+ default:
12
+ "border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",
13
+ secondary:
14
+ "border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",
15
+ destructive:
16
+ "border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",
17
+ outline:
18
+ "text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground",
19
+ },
20
+ },
21
+ defaultVariants: {
22
+ variant: "default",
23
+ },
24
+ },
25
+ )
26
+ export type BadgeVariants = VariantProps<typeof badgeVariants>
web/src/components/ui/card/Card.vue ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import type { HTMLAttributes } from "vue"
3
+ import { cn } from "@/lib/utils"
4
+
5
+ const props = defineProps<{
6
+ class?: HTMLAttributes["class"]
7
+ }>()
8
+ </script>
9
+
10
+ <template>
11
+ <div
12
+ data-slot="card"
13
+ :class="
14
+ cn(
15
+ 'bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm',
16
+ props.class,
17
+ )
18
+ "
19
+ >
20
+ <slot />
21
+ </div>
22
+ </template>
web/src/components/ui/card/CardAction.vue ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import type { HTMLAttributes } from "vue"
3
+ import { cn } from "@/lib/utils"
4
+
5
+ const props = defineProps<{
6
+ class?: HTMLAttributes["class"]
7
+ }>()
8
+ </script>
9
+
10
+ <template>
11
+ <div
12
+ data-slot="card-action"
13
+ :class="cn('col-start-2 row-span-2 row-start-1 self-start justify-self-end', props.class)"
14
+ >
15
+ <slot />
16
+ </div>
17
+ </template>
web/src/components/ui/card/CardContent.vue ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import type { HTMLAttributes } from "vue"
3
+ import { cn } from "@/lib/utils"
4
+
5
+ const props = defineProps<{
6
+ class?: HTMLAttributes["class"]
7
+ }>()
8
+ </script>
9
+
10
+ <template>
11
+ <div
12
+ data-slot="card-content"
13
+ :class="cn('px-6', props.class)"
14
+ >
15
+ <slot />
16
+ </div>
17
+ </template>
web/src/components/ui/card/CardDescription.vue ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import type { HTMLAttributes } from "vue"
3
+ import { cn } from "@/lib/utils"
4
+
5
+ const props = defineProps<{
6
+ class?: HTMLAttributes["class"]
7
+ }>()
8
+ </script>
9
+
10
+ <template>
11
+ <p
12
+ data-slot="card-description"
13
+ :class="cn('text-muted-foreground text-sm', props.class)"
14
+ >
15
+ <slot />
16
+ </p>
17
+ </template>
web/src/components/ui/card/CardFooter.vue ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import type { HTMLAttributes } from "vue"
3
+ import { cn } from "@/lib/utils"
4
+
5
+ const props = defineProps<{
6
+ class?: HTMLAttributes["class"]
7
+ }>()
8
+ </script>
9
+
10
+ <template>
11
+ <div
12
+ data-slot="card-footer"
13
+ :class="cn('flex items-center px-6 [.border-t]:pt-6', props.class)"
14
+ >
15
+ <slot />
16
+ </div>
17
+ </template>
web/src/components/ui/card/CardHeader.vue ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import type { HTMLAttributes } from "vue"
3
+ import { cn } from "@/lib/utils"
4
+
5
+ const props = defineProps<{
6
+ class?: HTMLAttributes["class"]
7
+ }>()
8
+ </script>
9
+
10
+ <template>
11
+ <div
12
+ data-slot="card-header"
13
+ :class="cn('@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-1.5 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6', props.class)"
14
+ >
15
+ <slot />
16
+ </div>
17
+ </template>
web/src/components/ui/card/CardTitle.vue ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import type { HTMLAttributes } from "vue"
3
+ import { cn } from "@/lib/utils"
4
+
5
+ const props = defineProps<{
6
+ class?: HTMLAttributes["class"]
7
+ }>()
8
+ </script>
9
+
10
+ <template>
11
+ <h3
12
+ data-slot="card-title"
13
+ :class="cn('leading-none font-semibold', props.class)"
14
+ >
15
+ <slot />
16
+ </h3>
17
+ </template>
web/src/components/ui/card/index.ts ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ export { default as Card } from "./Card.vue"
2
+ export { default as CardAction } from "./CardAction.vue"
3
+ export { default as CardContent } from "./CardContent.vue"
4
+ export { default as CardDescription } from "./CardDescription.vue"
5
+ export { default as CardFooter } from "./CardFooter.vue"
6
+ export { default as CardHeader } from "./CardHeader.vue"
7
+ export { default as CardTitle } from "./CardTitle.vue"
web/src/components/ui/dialog/Dialog.vue ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import type { DialogRootEmits, DialogRootProps } from "reka-ui"
3
+ import { DialogRoot, useForwardPropsEmits } from "reka-ui"
4
+
5
+ const props = defineProps<DialogRootProps>()
6
+ const emits = defineEmits<DialogRootEmits>()
7
+
8
+ const forwarded = useForwardPropsEmits(props, emits)
9
+ </script>
10
+
11
+ <template>
12
+ <DialogRoot
13
+ v-slot="slotProps"
14
+ data-slot="dialog"
15
+ v-bind="forwarded"
16
+ >
17
+ <slot v-bind="slotProps" />
18
+ </DialogRoot>
19
+ </template>
web/src/components/ui/dialog/DialogClose.vue ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import type { DialogCloseProps } from "reka-ui"
3
+ import { DialogClose } from "reka-ui"
4
+
5
+ const props = defineProps<DialogCloseProps>()
6
+ </script>
7
+
8
+ <template>
9
+ <DialogClose
10
+ data-slot="dialog-close"
11
+ v-bind="props"
12
+ >
13
+ <slot />
14
+ </DialogClose>
15
+ </template>
web/src/components/ui/dialog/DialogContent.vue ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import type { DialogContentEmits, DialogContentProps } from "reka-ui"
3
+ import type { HTMLAttributes } from "vue"
4
+ import { reactiveOmit } from "@vueuse/core"
5
+ import { X } from "lucide-vue-next"
6
+ import {
7
+ DialogClose,
8
+ DialogContent,
9
+ DialogPortal,
10
+ useForwardPropsEmits,
11
+ } from "reka-ui"
12
+ import { cn } from "@/lib/utils"
13
+ import DialogOverlay from "./DialogOverlay.vue"
14
+
15
+ defineOptions({
16
+ inheritAttrs: false,
17
+ })
18
+
19
+ const props = withDefaults(defineProps<DialogContentProps & { class?: HTMLAttributes["class"], showCloseButton?: boolean }>(), {
20
+ showCloseButton: true,
21
+ })
22
+ const emits = defineEmits<DialogContentEmits>()
23
+
24
+ const delegatedProps = reactiveOmit(props, "class")
25
+
26
+ const forwarded = useForwardPropsEmits(delegatedProps, emits)
27
+ </script>
28
+
29
+ <template>
30
+ <DialogPortal>
31
+ <DialogOverlay />
32
+ <DialogContent
33
+ data-slot="dialog-content"
34
+ v-bind="{ ...$attrs, ...forwarded }"
35
+ :class="
36
+ cn(
37
+ 'bg-background data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 fixed top-[50%] left-[50%] z-50 grid w-full max-w-[calc(100%-2rem)] translate-x-[-50%] translate-y-[-50%] gap-4 rounded-lg border p-6 shadow-lg duration-200 sm:max-w-lg',
38
+ props.class,
39
+ )"
40
+ >
41
+ <slot />
42
+
43
+ <DialogClose
44
+ v-if="showCloseButton"
45
+ data-slot="dialog-close"
46
+ class="ring-offset-background focus:ring-ring data-[state=open]:bg-accent data-[state=open]:text-muted-foreground absolute top-4 right-4 rounded-xs opacity-70 transition-opacity hover:opacity-100 focus:ring-2 focus:ring-offset-2 focus:outline-hidden disabled:pointer-events-none [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4"
47
+ >
48
+ <X />
49
+ <span class="sr-only">Close</span>
50
+ </DialogClose>
51
+ </DialogContent>
52
+ </DialogPortal>
53
+ </template>
web/src/components/ui/dialog/DialogDescription.vue ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import type { DialogDescriptionProps } from "reka-ui"
3
+ import type { HTMLAttributes } from "vue"
4
+ import { reactiveOmit } from "@vueuse/core"
5
+ import { DialogDescription, useForwardProps } from "reka-ui"
6
+ import { cn } from "@/lib/utils"
7
+
8
+ const props = defineProps<DialogDescriptionProps & { class?: HTMLAttributes["class"] }>()
9
+
10
+ const delegatedProps = reactiveOmit(props, "class")
11
+
12
+ const forwardedProps = useForwardProps(delegatedProps)
13
+ </script>
14
+
15
+ <template>
16
+ <DialogDescription
17
+ data-slot="dialog-description"
18
+ v-bind="forwardedProps"
19
+ :class="cn('text-muted-foreground text-sm', props.class)"
20
+ >
21
+ <slot />
22
+ </DialogDescription>
23
+ </template>
web/src/components/ui/dialog/DialogFooter.vue ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import type { HTMLAttributes } from "vue"
3
+ import { DialogClose } from "reka-ui"
4
+ import { cn } from "@/lib/utils"
5
+ import { Button } from '@/components/ui/button'
6
+
7
+ const props = withDefaults(defineProps<{
8
+ class?: HTMLAttributes["class"]
9
+ showCloseButton?: boolean
10
+ }>(), {
11
+ showCloseButton: false,
12
+ })
13
+ </script>
14
+
15
+ <template>
16
+ <div
17
+ data-slot="dialog-footer"
18
+ :class="cn('flex flex-col-reverse gap-2 sm:flex-row sm:justify-end', props.class)"
19
+ >
20
+ <slot />
21
+ <DialogClose v-if="showCloseButton" as-child>
22
+ <Button variant="outline">
23
+ Close
24
+ </Button>
25
+ </DialogClose>
26
+ </div>
27
+ </template>
web/src/components/ui/dialog/DialogHeader.vue ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import type { HTMLAttributes } from "vue"
3
+ import { cn } from "@/lib/utils"
4
+
5
+ const props = defineProps<{
6
+ class?: HTMLAttributes["class"]
7
+ }>()
8
+ </script>
9
+
10
+ <template>
11
+ <div
12
+ data-slot="dialog-header"
13
+ :class="cn('flex flex-col gap-2 text-center sm:text-left', props.class)"
14
+ >
15
+ <slot />
16
+ </div>
17
+ </template>
web/src/components/ui/dialog/DialogOverlay.vue ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import type { DialogOverlayProps } from "reka-ui"
3
+ import type { HTMLAttributes } from "vue"
4
+ import { reactiveOmit } from "@vueuse/core"
5
+ import { DialogOverlay } from "reka-ui"
6
+ import { cn } from "@/lib/utils"
7
+
8
+ const props = defineProps<DialogOverlayProps & { class?: HTMLAttributes["class"] }>()
9
+
10
+ const delegatedProps = reactiveOmit(props, "class")
11
+ </script>
12
+
13
+ <template>
14
+ <DialogOverlay
15
+ data-slot="dialog-overlay"
16
+ v-bind="delegatedProps"
17
+ :class="cn('data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 fixed inset-0 z-50 bg-black/80', props.class)"
18
+ >
19
+ <slot />
20
+ </DialogOverlay>
21
+ </template>
web/src/components/ui/dialog/DialogScrollContent.vue ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import type { DialogContentEmits, DialogContentProps } from "reka-ui"
3
+ import type { HTMLAttributes } from "vue"
4
+ import { reactiveOmit } from "@vueuse/core"
5
+ import { X } from "lucide-vue-next"
6
+ import {
7
+ DialogClose,
8
+ DialogContent,
9
+ DialogOverlay,
10
+ DialogPortal,
11
+ useForwardPropsEmits,
12
+ } from "reka-ui"
13
+ import { cn } from "@/lib/utils"
14
+
15
+ defineOptions({
16
+ inheritAttrs: false,
17
+ })
18
+
19
+ const props = defineProps<DialogContentProps & { class?: HTMLAttributes["class"] }>()
20
+ const emits = defineEmits<DialogContentEmits>()
21
+
22
+ const delegatedProps = reactiveOmit(props, "class")
23
+
24
+ const forwarded = useForwardPropsEmits(delegatedProps, emits)
25
+ </script>
26
+
27
+ <template>
28
+ <DialogPortal>
29
+ <DialogOverlay
30
+ class="fixed inset-0 z-50 grid place-items-center overflow-y-auto bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0"
31
+ >
32
+ <DialogContent
33
+ :class="
34
+ cn(
35
+ 'relative z-50 grid w-full max-w-lg my-8 gap-4 border border-border bg-background p-6 shadow-lg duration-200 sm:rounded-lg md:w-full',
36
+ props.class,
37
+ )
38
+ "
39
+ v-bind="{ ...$attrs, ...forwarded }"
40
+ @pointer-down-outside="(event) => {
41
+ const originalEvent = event.detail.originalEvent;
42
+ const target = originalEvent.target as HTMLElement;
43
+ if (originalEvent.offsetX > target.clientWidth || originalEvent.offsetY > target.clientHeight) {
44
+ event.preventDefault();
45
+ }
46
+ }"
47
+ >
48
+ <slot />
49
+
50
+ <DialogClose
51
+ class="absolute top-4 right-4 p-0.5 transition-colors rounded-md hover:bg-secondary"
52
+ >
53
+ <X class="w-4 h-4" />
54
+ <span class="sr-only">Close</span>
55
+ </DialogClose>
56
+ </DialogContent>
57
+ </DialogOverlay>
58
+ </DialogPortal>
59
+ </template>
web/src/components/ui/dialog/DialogTitle.vue ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import type { DialogTitleProps } from "reka-ui"
3
+ import type { HTMLAttributes } from "vue"
4
+ import { reactiveOmit } from "@vueuse/core"
5
+ import { DialogTitle, useForwardProps } from "reka-ui"
6
+ import { cn } from "@/lib/utils"
7
+
8
+ const props = defineProps<DialogTitleProps & { class?: HTMLAttributes["class"] }>()
9
+
10
+ const delegatedProps = reactiveOmit(props, "class")
11
+
12
+ const forwardedProps = useForwardProps(delegatedProps)
13
+ </script>
14
+
15
+ <template>
16
+ <DialogTitle
17
+ data-slot="dialog-title"
18
+ v-bind="forwardedProps"
19
+ :class="cn('text-lg leading-none font-semibold', props.class)"
20
+ >
21
+ <slot />
22
+ </DialogTitle>
23
+ </template>
web/src/components/ui/dialog/DialogTrigger.vue ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script setup lang="ts">
2
+ import type { DialogTriggerProps } from "reka-ui"
3
+ import { DialogTrigger } from "reka-ui"
4
+
5
+ const props = defineProps<DialogTriggerProps>()
6
+ </script>
7
+
8
+ <template>
9
+ <DialogTrigger
10
+ data-slot="dialog-trigger"
11
+ v-bind="props"
12
+ >
13
+ <slot />
14
+ </DialogTrigger>
15
+ </template>
web/src/components/ui/dialog/index.ts ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ export { default as Dialog } from "./Dialog.vue"
2
+ export { default as DialogClose } from "./DialogClose.vue"
3
+ export { default as DialogContent } from "./DialogContent.vue"
4
+ export { default as DialogDescription } from "./DialogDescription.vue"
5
+ export { default as DialogFooter } from "./DialogFooter.vue"
6
+ export { default as DialogHeader } from "./DialogHeader.vue"
7
+ export { default as DialogOverlay } from "./DialogOverlay.vue"
8
+ export { default as DialogScrollContent } from "./DialogScrollContent.vue"
9
+ export { default as DialogTitle } from "./DialogTitle.vue"
10
+ export { default as DialogTrigger } from "./DialogTrigger.vue"