Compare commits
1 Commits
018f7e12e4
...
f0b23960e7
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0b23960e7 |
1
Cargo.lock
generated
1
Cargo.lock
generated
@ -147,7 +147,6 @@ dependencies = [
|
|||||||
"prost",
|
"prost",
|
||||||
"prost-build",
|
"prost-build",
|
||||||
"prost-types",
|
"prost-types",
|
||||||
"rand 0.9.2",
|
|
||||||
"reqwest",
|
"reqwest",
|
||||||
"rocket",
|
"rocket",
|
||||||
"rocket_prost_responder_derive",
|
"rocket_prost_responder_derive",
|
||||||
|
|||||||
@ -19,7 +19,6 @@ serde_json = "1.0"
|
|||||||
reqwest = { version = "0.13", features = ["json"] }
|
reqwest = { version = "0.13", features = ["json"] }
|
||||||
aes-gcm = "0.10"
|
aes-gcm = "0.10"
|
||||||
base64 = "0.22"
|
base64 = "0.22"
|
||||||
rand = "0.9.2"
|
|
||||||
|
|
||||||
[build-dependencies]
|
[build-dependencies]
|
||||||
prost-build = "0.14"
|
prost-build = "0.14"
|
||||||
|
|||||||
@ -1,14 +1,13 @@
|
|||||||
use crate::auth_persistence::AuthStorage;
|
use crate::auth_persistence::AuthStorage;
|
||||||
use crate::csrf::{CsrfState, set_csrf_cookie};
|
|
||||||
use crate::items;
|
use crate::items;
|
||||||
use crate::proto_utils::Proto;
|
use crate::proto_utils::Proto;
|
||||||
use rocket::State;
|
use rocket::State;
|
||||||
use rocket::futures::lock::Mutex;
|
use rocket::futures::lock::Mutex;
|
||||||
use rocket::http::CookieJar;
|
|
||||||
use std::collections::{HashMap, HashSet};
|
use std::collections::{HashMap, HashSet};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
pub struct AuthState {
|
pub struct AuthState {
|
||||||
|
// Map token -> username
|
||||||
tokens: Mutex<HashMap<String, String>>,
|
tokens: Mutex<HashMap<String, String>>,
|
||||||
storage: AuthStorage,
|
storage: AuthStorage,
|
||||||
}
|
}
|
||||||
@ -66,6 +65,7 @@ impl<'r> rocket::request::FromRequest<'r> for Token {
|
|||||||
|
|
||||||
match token {
|
match token {
|
||||||
Some(token) => {
|
Some(token) => {
|
||||||
|
// Check if token starts with "Bearer "
|
||||||
if let Some(token) = token.strip_prefix("Bearer ") {
|
if let Some(token) = token.strip_prefix("Bearer ") {
|
||||||
let state = request.guard::<&State<AuthState>>().await.unwrap();
|
let state = request.guard::<&State<AuthState>>().await.unwrap();
|
||||||
let tokens = state.tokens.lock().await;
|
let tokens = state.tokens.lock().await;
|
||||||
@ -130,9 +130,7 @@ impl<'r> rocket::request::FromRequest<'r> for AdminToken {
|
|||||||
#[post("/login", data = "<request>")]
|
#[post("/login", data = "<request>")]
|
||||||
pub async fn login(
|
pub async fn login(
|
||||||
state: &State<AuthState>,
|
state: &State<AuthState>,
|
||||||
csrf_state: &State<CsrfState>,
|
|
||||||
user_list: &State<Mutex<Vec<crate::User>>>,
|
user_list: &State<Mutex<Vec<crate::User>>>,
|
||||||
jar: &CookieJar<'_>,
|
|
||||||
request: Proto<items::LoginRequest>,
|
request: Proto<items::LoginRequest>,
|
||||||
) -> items::LoginResponse {
|
) -> items::LoginResponse {
|
||||||
let req = request.into_inner();
|
let req = request.into_inner();
|
||||||
@ -148,9 +146,6 @@ pub async fn login(
|
|||||||
tokens.insert(token.clone(), req.username.clone());
|
tokens.insert(token.clone(), req.username.clone());
|
||||||
state.storage.save_tokens(&tokens);
|
state.storage.save_tokens(&tokens);
|
||||||
|
|
||||||
let csrf_token = csrf_state.generate_token();
|
|
||||||
set_csrf_cookie(jar, &csrf_token);
|
|
||||||
|
|
||||||
return items::LoginResponse {
|
return items::LoginResponse {
|
||||||
token,
|
token,
|
||||||
success: true,
|
success: true,
|
||||||
@ -191,8 +186,6 @@ pub async fn logout(
|
|||||||
pub async fn get_auth_status(
|
pub async fn get_auth_status(
|
||||||
state: &State<AuthState>,
|
state: &State<AuthState>,
|
||||||
admin_state: &State<AdminState>,
|
admin_state: &State<AdminState>,
|
||||||
csrf_state: &State<CsrfState>,
|
|
||||||
jar: &CookieJar<'_>,
|
|
||||||
request: Proto<items::AuthStatusRequest>,
|
request: Proto<items::AuthStatusRequest>,
|
||||||
) -> items::AuthStatusResponse {
|
) -> items::AuthStatusResponse {
|
||||||
let req = request.into_inner();
|
let req = request.into_inner();
|
||||||
@ -202,9 +195,6 @@ pub async fn get_auth_status(
|
|||||||
let admins = admin_state.admins.lock().await;
|
let admins = admin_state.admins.lock().await;
|
||||||
let is_admin = crate::store::is_admin(username, &admins);
|
let is_admin = crate::store::is_admin(username, &admins);
|
||||||
|
|
||||||
let csrf_token = csrf_state.generate_token();
|
|
||||||
set_csrf_cookie(jar, &csrf_token);
|
|
||||||
|
|
||||||
items::AuthStatusResponse {
|
items::AuthStatusResponse {
|
||||||
authenticated: true,
|
authenticated: true,
|
||||||
username: username.clone(),
|
username: username.clone(),
|
||||||
|
|||||||
@ -185,7 +185,7 @@ impl AuthStorage {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
let nonce_bytes: [u8; NONCE_SIZE] = rand::random();
|
let nonce_bytes: [u8; NONCE_SIZE] = rand::thread_rng().generate_bytes();
|
||||||
let nonce = Nonce::from_slice(&nonce_bytes);
|
let nonce = Nonce::from_slice(&nonce_bytes);
|
||||||
let ciphertext = match self.cipher.encrypt(nonce, plaintext.as_ref()) {
|
let ciphertext = match self.cipher.encrypt(nonce, plaintext.as_ref()) {
|
||||||
Ok(encrypted) => encrypted,
|
Ok(encrypted) => encrypted,
|
||||||
@ -225,3 +225,37 @@ impl AuthStorage {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
mod rand {
|
||||||
|
use std::cell::Cell;
|
||||||
|
|
||||||
|
thread_local! {
|
||||||
|
static STATE: Cell<u64> = Cell::new(
|
||||||
|
std::time::SystemTime::now()
|
||||||
|
.duration_since(std::time::UNIX_EPOCH)
|
||||||
|
.unwrap_or_default()
|
||||||
|
.as_nanos() as u64
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct ThreadRng;
|
||||||
|
|
||||||
|
pub fn thread_rng() -> ThreadRng {
|
||||||
|
ThreadRng
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ThreadRng {
|
||||||
|
pub fn generate_bytes<const N: usize>(&mut self) -> [u8; N] {
|
||||||
|
let mut result = [0u8; N];
|
||||||
|
STATE.with(|state| {
|
||||||
|
let mut s = state.get();
|
||||||
|
for byte in result.iter_mut() {
|
||||||
|
s = s.wrapping_mul(1103515245).wrapping_add(12345);
|
||||||
|
*byte = (s >> (s % 8)) as u8;
|
||||||
|
}
|
||||||
|
state.set(s);
|
||||||
|
});
|
||||||
|
result
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@ -1,95 +0,0 @@
|
|||||||
use rocket::Build;
|
|
||||||
use rocket::Request;
|
|
||||||
use rocket::Rocket;
|
|
||||||
use rocket::fairing::{Fairing, Info, Kind};
|
|
||||||
use rocket::http::{Cookie, CookieJar, SameSite, Status};
|
|
||||||
use rocket::request::{FromRequest, Outcome};
|
|
||||||
use std::collections::HashSet;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use uuid::Uuid;
|
|
||||||
|
|
||||||
const CSRF_COOKIE_NAME: &str = "csrf_token";
|
|
||||||
const CSRF_HEADER_NAME: &str = "X-CSRF-Token";
|
|
||||||
const CSRF_EXPIRATION_HOURS: u64 = 24;
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct CsrfToken(pub String);
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct CsrfState {
|
|
||||||
tokens: Arc<std::sync::Mutex<HashSet<String>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CsrfState {
|
|
||||||
pub fn new() -> Self {
|
|
||||||
Self {
|
|
||||||
tokens: Arc::new(std::sync::Mutex::new(HashSet::new())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn generate_token(&self) -> String {
|
|
||||||
let token = Uuid::new_v4().to_string();
|
|
||||||
self.tokens.lock().unwrap().insert(token.clone());
|
|
||||||
token
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn validate_token(&self, token: &str) -> bool {
|
|
||||||
self.tokens.lock().unwrap().remove(token)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for CsrfState {
|
|
||||||
fn default() -> Self {
|
|
||||||
Self::new()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[rocket::async_trait]
|
|
||||||
impl<'r> FromRequest<'r> for CsrfToken {
|
|
||||||
type Error = ();
|
|
||||||
|
|
||||||
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
|
|
||||||
let header_token = request.headers().get_one(CSRF_HEADER_NAME);
|
|
||||||
let cookie_jar = request.guard::<&CookieJar<'_>>().await;
|
|
||||||
|
|
||||||
let cookie_token = match cookie_jar {
|
|
||||||
Outcome::Success(jar) => jar
|
|
||||||
.get(CSRF_COOKIE_NAME)
|
|
||||||
.map(|c: &Cookie<'_>| c.value().to_string()),
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
|
|
||||||
match (header_token, cookie_token) {
|
|
||||||
(Some(header), Some(cookie)) if header == cookie => {
|
|
||||||
Outcome::Success(CsrfToken(header.to_string()))
|
|
||||||
}
|
|
||||||
_ => Outcome::Error((Status::Forbidden, ())),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub struct CsrfFairing;
|
|
||||||
|
|
||||||
#[rocket::async_trait]
|
|
||||||
impl Fairing for CsrfFairing {
|
|
||||||
fn info(&self) -> Info {
|
|
||||||
Info {
|
|
||||||
name: "CSRF Protection",
|
|
||||||
kind: Kind::Ignite,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_ignite(&self, rocket: Rocket<Build>) -> Result<Rocket<Build>, Rocket<Build>> {
|
|
||||||
Ok(rocket.manage(CsrfState::new()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn set_csrf_cookie(jar: &CookieJar<'_>, token: &str) {
|
|
||||||
jar.add(
|
|
||||||
Cookie::build((CSRF_COOKIE_NAME, token.to_owned()))
|
|
||||||
.http_only(true)
|
|
||||||
.same_site(SameSite::Strict)
|
|
||||||
.max_age(rocket::time::Duration::hours(CSRF_EXPIRATION_HOURS as i64))
|
|
||||||
.path("/"),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@ -7,13 +7,8 @@ pub mod items {
|
|||||||
|
|
||||||
pub mod auth;
|
pub mod auth;
|
||||||
pub mod auth_persistence;
|
pub mod auth_persistence;
|
||||||
pub mod csrf;
|
|
||||||
pub mod proto_utils;
|
pub mod proto_utils;
|
||||||
pub mod security_headers;
|
|
||||||
pub mod store;
|
pub mod store;
|
||||||
pub mod validation;
|
|
||||||
|
|
||||||
pub use auth::AdminState;
|
pub use auth::AdminState;
|
||||||
pub use csrf::{CsrfFairing, CsrfState, CsrfToken, set_csrf_cookie};
|
|
||||||
pub use security_headers::SecurityHeaders;
|
|
||||||
pub use store::User;
|
pub use store::User;
|
||||||
|
|||||||
@ -4,12 +4,9 @@ use rocket::futures::lock::Mutex;
|
|||||||
|
|
||||||
use backend::auth;
|
use backend::auth;
|
||||||
use backend::auth::AdminState;
|
use backend::auth::AdminState;
|
||||||
use backend::csrf::{CsrfFairing, CsrfToken};
|
|
||||||
use backend::items::{self, Game};
|
use backend::items::{self, Game};
|
||||||
use backend::proto_utils;
|
use backend::proto_utils;
|
||||||
use backend::security_headers::SecurityHeaders;
|
|
||||||
use backend::store::{self, User, save_state};
|
use backend::store::{self, User, save_state};
|
||||||
use backend::validation;
|
|
||||||
|
|
||||||
#[macro_use]
|
#[macro_use]
|
||||||
extern crate rocket;
|
extern crate rocket;
|
||||||
@ -20,10 +17,6 @@ async fn get_user(
|
|||||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||||
name: &str,
|
name: &str,
|
||||||
) -> Option<items::Person> {
|
) -> Option<items::Person> {
|
||||||
if validation::validate_username(name).is_err() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let users = user_list.lock().await;
|
let users = user_list.lock().await;
|
||||||
users
|
users
|
||||||
.iter()
|
.iter()
|
||||||
@ -48,10 +41,6 @@ async fn get_game(
|
|||||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||||
title: &str,
|
title: &str,
|
||||||
) -> Option<items::Game> {
|
) -> Option<items::Game> {
|
||||||
if validation::validate_game_title(title).is_err() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
|
|
||||||
let games = game_list.lock().await;
|
let games = game_list.lock().await;
|
||||||
games
|
games
|
||||||
.iter()
|
.iter()
|
||||||
@ -64,16 +53,12 @@ async fn get_games_batch(
|
|||||||
_token: auth::Token,
|
_token: auth::Token,
|
||||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||||
req: proto_utils::Proto<items::GetGameInfoRequest>,
|
req: proto_utils::Proto<items::GetGameInfoRequest>,
|
||||||
) -> Result<items::GameList, String> {
|
) -> items::GameList {
|
||||||
let req = req.into_inner();
|
|
||||||
|
|
||||||
let games_set: std::collections::HashSet<String> = req.games.into_iter().collect();
|
|
||||||
validation::validate_game_titles_batch(&games_set)?;
|
|
||||||
|
|
||||||
let games = game_list.lock().await;
|
let games = game_list.lock().await;
|
||||||
|
let req = req.into_inner();
|
||||||
let mut games = games.clone();
|
let mut games = games.clone();
|
||||||
games.retain(|g| games_set.contains(&g.title));
|
games.retain(|g| req.games.contains(&g.title));
|
||||||
Ok(items::GameList { games })
|
items::GameList { games }
|
||||||
}
|
}
|
||||||
|
|
||||||
#[get("/games")]
|
#[get("/games")]
|
||||||
@ -87,77 +72,55 @@ async fn get_games(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[post("/game", data = "<game>", rank = 1)]
|
#[post("/game", data = "<game>")]
|
||||||
async fn add_game(
|
async fn add_game(
|
||||||
_token: auth::Token,
|
_token: auth::Token,
|
||||||
_csrf: CsrfToken,
|
|
||||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||||
game: proto_utils::Proto<items::Game>,
|
game: proto_utils::Proto<items::Game>,
|
||||||
) -> Result<Option<items::Game>, String> {
|
) -> Option<items::Game> {
|
||||||
|
let mut games = game_list.lock().await;
|
||||||
let mut game = game.into_inner();
|
let mut game = game.into_inner();
|
||||||
|
|
||||||
game.title = game.title.trim().to_string();
|
game.title = game.title.trim().to_string();
|
||||||
|
|
||||||
validation::validate_game_title(&game.title)?;
|
if game.remote_id == 0 {
|
||||||
validation::validate_remote_id(game.remote_id)?;
|
return None;
|
||||||
validation::validate_player_count(game.min_players, game.max_players)?;
|
|
||||||
validation::validate_price(game.price)?;
|
|
||||||
|
|
||||||
if game.title.len() > validation::MAX_GAME_TITLE_TRIMMED_LENGTH {
|
|
||||||
game.title = game
|
|
||||||
.title
|
|
||||||
.chars()
|
|
||||||
.take(validation::MAX_GAME_TITLE_TRIMMED_LENGTH)
|
|
||||||
.collect();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let users = user_list.lock().await;
|
|
||||||
let mut games = game_list.lock().await;
|
|
||||||
|
|
||||||
if let Some(existing) = games.iter().find(|g| {
|
if let Some(existing) = games.iter().find(|g| {
|
||||||
g.title == game.title || (g.remote_id == game.remote_id && g.source == game.source)
|
g.title == game.title || (g.remote_id == game.remote_id && g.source == game.source)
|
||||||
}) {
|
}) {
|
||||||
return Ok(Some(existing.clone()));
|
return Some(existing.clone());
|
||||||
}
|
}
|
||||||
|
|
||||||
games.push(game.clone());
|
games.push(game.clone());
|
||||||
|
|
||||||
games.sort_unstable_by(|g1, g2| g1.title.cmp(&g2.title));
|
games.sort_unstable_by(|g1, g2| g1.title.cmp(&g2.title));
|
||||||
|
|
||||||
|
let users = user_list.lock().await;
|
||||||
save_state(&games, &users);
|
save_state(&games, &users);
|
||||||
|
|
||||||
Ok(Some(game))
|
Some(game)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[patch("/game", data = "<game>", rank = 1)]
|
#[patch("/game", data = "<game>")]
|
||||||
async fn update_game(
|
async fn update_game(
|
||||||
_token: auth::AdminToken,
|
_token: auth::AdminToken,
|
||||||
_csrf: CsrfToken,
|
|
||||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||||
game: proto_utils::Proto<items::Game>,
|
game: proto_utils::Proto<items::Game>,
|
||||||
) -> Result<Option<items::Game>, String> {
|
) -> Option<items::Game> {
|
||||||
|
let mut games = game_list.lock().await;
|
||||||
|
let mut users = user_list.lock().await;
|
||||||
let mut game = game.into_inner();
|
let mut game = game.into_inner();
|
||||||
|
|
||||||
game.title = game.title.trim().to_string();
|
game.title = game.title.trim().to_string();
|
||||||
|
|
||||||
validation::validate_game_title(&game.title)?;
|
if game.remote_id == 0 {
|
||||||
validation::validate_remote_id(game.remote_id)?;
|
return None;
|
||||||
validation::validate_player_count(game.min_players, game.max_players)?;
|
|
||||||
validation::validate_price(game.price)?;
|
|
||||||
|
|
||||||
if game.title.len() > validation::MAX_GAME_TITLE_TRIMMED_LENGTH {
|
|
||||||
game.title = game
|
|
||||||
.title
|
|
||||||
.chars()
|
|
||||||
.take(validation::MAX_GAME_TITLE_TRIMMED_LENGTH)
|
|
||||||
.collect();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut users = user_list.lock().await;
|
|
||||||
let mut games = game_list.lock().await;
|
|
||||||
|
|
||||||
let mut r_existing = None;
|
let mut r_existing = None;
|
||||||
|
|
||||||
if let Some(existing) = games.iter_mut().find(|g| {
|
if let Some(existing) = games.iter_mut().find(|g| {
|
||||||
@ -165,6 +128,7 @@ async fn update_game(
|
|||||||
}) {
|
}) {
|
||||||
if existing.title != game.title {
|
if existing.title != game.title {
|
||||||
let old_title = existing.title.clone();
|
let old_title = existing.title.clone();
|
||||||
|
// Update title for every opinion
|
||||||
for person in users.iter_mut() {
|
for person in users.iter_mut() {
|
||||||
let opinion = person
|
let opinion = person
|
||||||
.person
|
.person
|
||||||
@ -190,20 +154,16 @@ async fn update_game(
|
|||||||
|
|
||||||
save_state(&games, &users);
|
save_state(&games, &users);
|
||||||
|
|
||||||
Ok(r_existing)
|
r_existing
|
||||||
}
|
}
|
||||||
|
|
||||||
#[delete("/game/<title>", rank = 1)]
|
#[delete("/game/<title>")]
|
||||||
async fn delete_game(
|
async fn delete_game(
|
||||||
_token: auth::AdminToken,
|
_token: auth::AdminToken,
|
||||||
_csrf: CsrfToken,
|
|
||||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||||
title: &str,
|
title: &str,
|
||||||
) -> Result<Option<items::Game>, String> {
|
) -> Option<items::Game> {
|
||||||
validation::validate_game_title(title)?;
|
|
||||||
|
|
||||||
let mut users = user_list.lock().await;
|
|
||||||
let mut games = game_list.lock().await;
|
let mut games = game_list.lock().await;
|
||||||
|
|
||||||
if let Some(pos) = games
|
if let Some(pos) = games
|
||||||
@ -212,29 +172,30 @@ async fn delete_game(
|
|||||||
{
|
{
|
||||||
let game = games.remove(pos);
|
let game = games.remove(pos);
|
||||||
|
|
||||||
|
let mut users = user_list.lock().await;
|
||||||
|
|
||||||
for person in users.iter_mut() {
|
for person in users.iter_mut() {
|
||||||
person.person.opinion.retain_mut(|o| o.title != game.title);
|
person.person.opinion.retain_mut(|o| o.title != game.title);
|
||||||
}
|
}
|
||||||
|
|
||||||
save_state(&games, &users);
|
save_state(&games, &users);
|
||||||
|
|
||||||
return Ok(Some(game));
|
return Some(game);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(None)
|
None
|
||||||
}
|
}
|
||||||
|
|
||||||
#[post("/refresh", rank = 1)]
|
#[post("/refresh")]
|
||||||
async fn refresh_state(
|
async fn refresh_state(
|
||||||
_token: auth::AdminToken,
|
_token: auth::AdminToken,
|
||||||
_csrf: CsrfToken,
|
|
||||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||||
admin_state: &rocket::State<AdminState>,
|
admin_state: &rocket::State<AdminState>,
|
||||||
) -> items::RefreshResponse {
|
) -> items::RefreshResponse {
|
||||||
if let Some((new_games, new_users)) = store::load_state() {
|
if let Some((new_games, new_users)) = store::load_state() {
|
||||||
let mut users = user_list.lock().await;
|
|
||||||
let mut games = game_list.lock().await;
|
let mut games = game_list.lock().await;
|
||||||
|
let mut users = user_list.lock().await;
|
||||||
let mut admins = admin_state.admins.lock().await;
|
let mut admins = admin_state.admins.lock().await;
|
||||||
|
|
||||||
*games = new_games;
|
*games = new_games;
|
||||||
@ -253,22 +214,20 @@ async fn refresh_state(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[post("/opinion", data = "<req>", rank = 1)]
|
#[post("/opinion", data = "<req>")]
|
||||||
async fn add_opinion(
|
async fn add_opinion(
|
||||||
token: auth::Token,
|
token: auth::Token,
|
||||||
_csrf: CsrfToken,
|
|
||||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||||
req: proto_utils::Proto<items::AddOpinionRequest>,
|
req: proto_utils::Proto<items::AddOpinionRequest>,
|
||||||
) -> Result<Option<items::Person>, String> {
|
) -> Option<items::Person> {
|
||||||
validation::validate_username(&token.username)?;
|
|
||||||
|
|
||||||
let games = game_list.lock().await;
|
let games = game_list.lock().await;
|
||||||
let mut users = user_list.lock().await;
|
let mut users = user_list.lock().await;
|
||||||
let mut result = None;
|
let mut result = None;
|
||||||
|
|
||||||
|
// Validate game exists
|
||||||
if !games.iter().any(|g| g.title == req.game_title) {
|
if !games.iter().any(|g| g.title == req.game_title) {
|
||||||
return Err("Game not found".to_string());
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
if let Some(user) = users
|
if let Some(user) = users
|
||||||
@ -276,8 +235,6 @@ async fn add_opinion(
|
|||||||
.find(|u| u.person.name.to_lowercase() == token.username.to_lowercase())
|
.find(|u| u.person.name.to_lowercase() == token.username.to_lowercase())
|
||||||
{
|
{
|
||||||
let req = req.into_inner();
|
let req = req.into_inner();
|
||||||
validation::validate_game_title(&req.game_title)?;
|
|
||||||
|
|
||||||
let opinion = items::Opinion {
|
let opinion = items::Opinion {
|
||||||
title: req.game_title.clone(),
|
title: req.game_title.clone(),
|
||||||
would_play: req.would_play,
|
would_play: req.would_play,
|
||||||
@ -303,19 +260,16 @@ async fn add_opinion(
|
|||||||
if result.is_some() {
|
if result.is_some() {
|
||||||
save_state(&games, &users);
|
save_state(&games, &users);
|
||||||
}
|
}
|
||||||
Ok(result)
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
#[patch("/opinion", data = "<req>", rank = 1)]
|
#[patch("/opinion", data = "<req>")]
|
||||||
async fn remove_opinion(
|
async fn remove_opinion(
|
||||||
token: auth::Token,
|
token: auth::Token,
|
||||||
_csrf: CsrfToken,
|
|
||||||
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
game_list: &rocket::State<Mutex<Vec<Game>>>,
|
||||||
user_list: &rocket::State<Mutex<Vec<User>>>,
|
user_list: &rocket::State<Mutex<Vec<User>>>,
|
||||||
req: proto_utils::Proto<items::RemoveOpinionRequest>,
|
req: proto_utils::Proto<items::RemoveOpinionRequest>,
|
||||||
) -> Result<Option<items::Person>, String> {
|
) -> Option<items::Person> {
|
||||||
validation::validate_username(&token.username)?;
|
|
||||||
|
|
||||||
let games = game_list.lock().await;
|
let games = game_list.lock().await;
|
||||||
let mut users = user_list.lock().await;
|
let mut users = user_list.lock().await;
|
||||||
let mut result = None;
|
let mut result = None;
|
||||||
@ -325,7 +279,6 @@ async fn remove_opinion(
|
|||||||
.find(|u| u.person.name.to_lowercase() == token.username.to_lowercase())
|
.find(|u| u.person.name.to_lowercase() == token.username.to_lowercase())
|
||||||
{
|
{
|
||||||
let req = req.into_inner();
|
let req = req.into_inner();
|
||||||
validation::validate_game_title(&req.game_title)?;
|
|
||||||
|
|
||||||
if let Some(existing) = user
|
if let Some(existing) = user
|
||||||
.person
|
.person
|
||||||
@ -341,7 +294,7 @@ async fn remove_opinion(
|
|||||||
if result.is_some() {
|
if result.is_some() {
|
||||||
save_state(&games, &users);
|
save_state(&games, &users);
|
||||||
}
|
}
|
||||||
Ok(result)
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
mod cached_option;
|
mod cached_option;
|
||||||
@ -494,8 +447,6 @@ async fn main() -> Result<(), std::io::Error> {
|
|||||||
});
|
});
|
||||||
|
|
||||||
rocket::build()
|
rocket::build()
|
||||||
.attach(SecurityHeaders)
|
|
||||||
.attach(CsrfFairing)
|
|
||||||
.manage(Mutex::new(user_list))
|
.manage(Mutex::new(user_list))
|
||||||
.manage(auth::AuthState::new())
|
.manage(auth::AuthState::new())
|
||||||
.manage(auth::AdminState::new())
|
.manage(auth::AdminState::new())
|
||||||
|
|||||||
@ -1,33 +0,0 @@
|
|||||||
use rocket::fairing::{Fairing, Info, Kind};
|
|
||||||
use rocket::http::Header;
|
|
||||||
use rocket::{Request, Response};
|
|
||||||
|
|
||||||
pub struct SecurityHeaders;
|
|
||||||
|
|
||||||
#[rocket::async_trait]
|
|
||||||
impl Fairing for SecurityHeaders {
|
|
||||||
fn info(&self) -> Info {
|
|
||||||
Info {
|
|
||||||
name: "Security Headers",
|
|
||||||
kind: Kind::Response,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn on_response<'r>(&self, _request: &'r Request<'_>, response: &mut Response<'r>) {
|
|
||||||
response.set_header(Header::new("X-Content-Type-Options", "nosniff"));
|
|
||||||
response.set_header(Header::new("X-Frame-Options", "DENY"));
|
|
||||||
response.set_header(Header::new("X-XSS-Protection", "1; mode=block"));
|
|
||||||
response.set_header(Header::new(
|
|
||||||
"Referrer-Policy",
|
|
||||||
"strict-origin-when-cross-origin",
|
|
||||||
));
|
|
||||||
response.set_header(Header::new(
|
|
||||||
"Content-Security-Policy",
|
|
||||||
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self'; frame-ancestors 'none';",
|
|
||||||
));
|
|
||||||
response.set_header(Header::new(
|
|
||||||
"Permissions-Policy",
|
|
||||||
"geolocation=(), microphone=(), camera=()",
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,108 +0,0 @@
|
|||||||
use std::collections::HashSet;
|
|
||||||
|
|
||||||
pub const MAX_USERNAME_LENGTH: usize = 50;
|
|
||||||
pub const MIN_USERNAME_LENGTH: usize = 2;
|
|
||||||
pub const MAX_GAME_TITLE_LENGTH: usize = 200;
|
|
||||||
const MIN_GAME_TITLE_LENGTH: usize = 1;
|
|
||||||
pub const MAX_GAME_TITLE_TRIMMED_LENGTH: usize = 200;
|
|
||||||
pub const MAX_PRICE: u32 = 1_000_000;
|
|
||||||
pub const MAX_PLAYERS: u32 = 10_000;
|
|
||||||
|
|
||||||
const VALID_USERNAME_CHARS: &str =
|
|
||||||
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
|
|
||||||
|
|
||||||
pub fn validate_username(username: &str) -> Result<(), String> {
|
|
||||||
let trimmed = username.trim();
|
|
||||||
|
|
||||||
if trimmed.is_empty() {
|
|
||||||
return Err("Username cannot be empty".to_string());
|
|
||||||
}
|
|
||||||
|
|
||||||
if trimmed.len() < MIN_USERNAME_LENGTH {
|
|
||||||
return Err(format!(
|
|
||||||
"Username must be at least {} characters long",
|
|
||||||
MIN_USERNAME_LENGTH
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
if trimmed.len() > MAX_USERNAME_LENGTH {
|
|
||||||
return Err(format!(
|
|
||||||
"Username must not exceed {} characters",
|
|
||||||
MAX_USERNAME_LENGTH
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
for c in trimmed.chars() {
|
|
||||||
if !VALID_USERNAME_CHARS.contains(c) {
|
|
||||||
return Err(format!(
|
|
||||||
"Username contains invalid character '{}'. Only alphanumeric characters, underscores and hyphens are allowed",
|
|
||||||
c
|
|
||||||
));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn validate_game_title(title: &str) -> Result<(), String> {
|
|
||||||
if title.trim().is_empty() {
|
|
||||||
return Err("Game title cannot be empty".to_string());
|
|
||||||
}
|
|
||||||
|
|
||||||
if title.len() > MAX_GAME_TITLE_LENGTH {
|
|
||||||
return Err(format!(
|
|
||||||
"Game title must not exceed {} characters",
|
|
||||||
MAX_GAME_TITLE_LENGTH
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn validate_remote_id(remote_id: u64) -> Result<(), String> {
|
|
||||||
if remote_id == 0 {
|
|
||||||
return Err("Remote ID cannot be zero".to_string());
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn validate_player_count(min_players: u32, max_players: u32) -> Result<(), String> {
|
|
||||||
if min_players == 0 {
|
|
||||||
return Err("Minimum players must be at least 1".to_string());
|
|
||||||
}
|
|
||||||
|
|
||||||
if min_players > max_players {
|
|
||||||
return Err("Minimum players cannot be greater than maximum players".to_string());
|
|
||||||
}
|
|
||||||
|
|
||||||
if max_players > MAX_PLAYERS {
|
|
||||||
return Err(format!("Maximum players cannot exceed {}", MAX_PLAYERS));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn validate_price(price: u32) -> Result<(), String> {
|
|
||||||
if price > MAX_PRICE {
|
|
||||||
return Err(format!("Price cannot exceed ${}", MAX_PRICE));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn validate_game_titles_batch(titles: &HashSet<String>) -> Result<(), String> {
|
|
||||||
if titles.is_empty() {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
|
|
||||||
if titles.len() > 100 {
|
|
||||||
return Err("Cannot request more than 100 games at once".to_string());
|
|
||||||
}
|
|
||||||
|
|
||||||
for title in titles {
|
|
||||||
validate_game_title(title)?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
@ -1,6 +1,6 @@
|
|||||||
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
|
// Code generated by protoc-gen-ts_proto. DO NOT EDIT.
|
||||||
// versions:
|
// versions:
|
||||||
// protoc-gen-ts_proto v2.10.1
|
// protoc-gen-ts_proto v2.8.3
|
||||||
// protoc v6.33.1
|
// protoc v6.33.1
|
||||||
// source: items.proto
|
// source: items.proto
|
||||||
|
|
||||||
|
|||||||
@ -1,26 +1,16 @@
|
|||||||
import { AuthStatusRequest, AuthStatusResponse } from "../items";
|
import { AuthStatusRequest, AuthStatusResponse } from "../items";
|
||||||
|
|
||||||
export const getCsrfToken = (): string | null => {
|
|
||||||
const match = document.cookie.match(/csrf_token=([^;]+)/);
|
|
||||||
return match ? decodeURIComponent(match[1]) : null;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const apiFetch = async (
|
export const apiFetch = async (
|
||||||
url: string,
|
url: string,
|
||||||
options: RequestInit = {}
|
options: RequestInit = {}
|
||||||
): Promise<Response> => {
|
): Promise<Response> => {
|
||||||
const token = localStorage.getItem("token");
|
const token = localStorage.getItem("token");
|
||||||
const csrfToken = getCsrfToken();
|
|
||||||
const headers = new Headers(options.headers);
|
const headers = new Headers(options.headers);
|
||||||
|
|
||||||
if (token) {
|
if (token) {
|
||||||
headers.set("Authorization", `Bearer ${token}`);
|
headers.set("Authorization", `Bearer ${token}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (csrfToken) {
|
|
||||||
headers.set("X-CSRF-Token", csrfToken);
|
|
||||||
}
|
|
||||||
|
|
||||||
const config = {
|
const config = {
|
||||||
...options,
|
...options,
|
||||||
headers,
|
headers,
|
||||||
|
|||||||
@ -35,11 +35,7 @@ export function FilteredGamesList({
|
|||||||
const positiveCount = gameToPositive.get(game)?.size || 0;
|
const positiveCount = gameToPositive.get(game)?.size || 0;
|
||||||
const neutralCount = selectedPeopleCount - positiveCount;
|
const neutralCount = selectedPeopleCount - positiveCount;
|
||||||
const gameData = games.get(game);
|
const gameData = games.get(game);
|
||||||
if (!gameData) {
|
const price = gameData?.price ?? 0;
|
||||||
console.error("no data", game);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
const price = gameData.price;
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
@ -85,10 +81,7 @@ export function FilteredGamesList({
|
|||||||
padding: "0.2rem 0.6rem",
|
padding: "0.2rem 0.6rem",
|
||||||
borderRadius: "4px",
|
borderRadius: "4px",
|
||||||
display: "inline-block",
|
display: "inline-block",
|
||||||
backgroundColor:
|
backgroundColor: price === 0 ? "rgba(76, 175, 80, 0.2)" : "rgba(255, 152, 0, 0.2)",
|
||||||
price === 0
|
|
||||||
? "rgba(76, 175, 80, 0.2)"
|
|
||||||
: "rgba(255, 152, 0, 0.2)",
|
|
||||||
color: price === 0 ? "#4caf50" : "#ff9800",
|
color: price === 0 ? "#4caf50" : "#ff9800",
|
||||||
fontWeight: 600,
|
fontWeight: 600,
|
||||||
}}
|
}}
|
||||||
|
|||||||
@ -112,7 +112,9 @@ export function useGameFilter(
|
|||||||
selectedPeople,
|
selectedPeople,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const gamesMap = new Map(Object.entries(metaDataRef.current));
|
const gamesMap = useMemo(() => {
|
||||||
|
return new Map(Object.entries(metaDataRef.current));
|
||||||
|
}, []);
|
||||||
|
|
||||||
return { filteredGames, gameToPositive: gameToPositiveOpinion, games: gamesMap };
|
return { filteredGames, gameToPositive: gameToPositiveOpinion, games: gamesMap };
|
||||||
}
|
}
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user