Author SHA1 Message Date
Renovate Bot 055e433b14 Update dependency @bufbuild/protobuf to v2.13.0 2026-07-21 12:04:21 +00:00
code002lover f3dba4c483 remove csrf 2026-01-19 17:15:34 +01:00
code002lover 5584299d44 fix CSP 2026-01-19 16:20:55 +01:00
code002lover 97ac27e78a fix no data error 2026-01-19 16:18:31 +01:00
9 changed files with 18 additions and 140 deletions
-12
View File
@@ -1,10 +1,8 @@
use crate::auth_persistence::AuthStorage;
use crate::csrf::{CsrfState, set_csrf_cookie};
use crate::items;
use crate::proto_utils::Proto;
use rocket::State;
use rocket::futures::lock::Mutex;
use rocket::http::CookieJar;
use std::collections::{HashMap, HashSet};
use uuid::Uuid;
@@ -130,9 +128,7 @@ impl<'r> rocket::request::FromRequest<'r> for AdminToken {
#[post("/login", data = "<request>")]
pub async fn login(
state: &State<AuthState>,
csrf_state: &State<CsrfState>,
user_list: &State<Mutex<Vec<crate::User>>>,
jar: &CookieJar<'_>,
request: Proto<items::LoginRequest>,
) -> items::LoginResponse {
let req = request.into_inner();
@@ -148,9 +144,6 @@ pub async fn login(
tokens.insert(token.clone(), req.username.clone());
state.storage.save_tokens(&tokens);
let csrf_token = csrf_state.generate_token();
set_csrf_cookie(jar, &csrf_token);
return items::LoginResponse {
token,
success: true,
@@ -191,8 +184,6 @@ pub async fn logout(
pub async fn get_auth_status(
state: &State<AuthState>,
admin_state: &State<AdminState>,
csrf_state: &State<CsrfState>,
jar: &CookieJar<'_>,
request: Proto<items::AuthStatusRequest>,
) -> items::AuthStatusResponse {
let req = request.into_inner();
@@ -202,9 +193,6 @@ pub async fn get_auth_status(
let admins = admin_state.admins.lock().await;
let is_admin = crate::store::is_admin(username, &admins);
let csrf_token = csrf_state.generate_token();
set_csrf_cookie(jar, &csrf_token);
items::AuthStatusResponse {
authenticated: true,
username: username.clone(),
-95
View File
@@ -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("/"),
);
}
-2
View File
@@ -7,13 +7,11 @@ pub mod items {
pub mod auth;
pub mod auth_persistence;
pub mod csrf;
pub mod proto_utils;
pub mod security_headers;
pub mod store;
pub mod validation;
pub use auth::AdminState;
pub use csrf::{CsrfFairing, CsrfState, CsrfToken, set_csrf_cookie};
pub use security_headers::SecurityHeaders;
pub use store::User;
-8
View File
@@ -4,7 +4,6 @@ use rocket::futures::lock::Mutex;
use backend::auth;
use backend::auth::AdminState;
use backend::csrf::{CsrfFairing, CsrfToken};
use backend::items::{self, Game};
use backend::proto_utils;
use backend::security_headers::SecurityHeaders;
@@ -90,7 +89,6 @@ async fn get_games(
#[post("/game", data = "<game>", rank = 1)]
async fn add_game(
_token: auth::Token,
_csrf: CsrfToken,
game_list: &rocket::State<Mutex<Vec<Game>>>,
user_list: &rocket::State<Mutex<Vec<User>>>,
game: proto_utils::Proto<items::Game>,
@@ -133,7 +131,6 @@ async fn add_game(
#[patch("/game", data = "<game>", rank = 1)]
async fn update_game(
_token: auth::AdminToken,
_csrf: CsrfToken,
game_list: &rocket::State<Mutex<Vec<Game>>>,
user_list: &rocket::State<Mutex<Vec<User>>>,
game: proto_utils::Proto<items::Game>,
@@ -196,7 +193,6 @@ async fn update_game(
#[delete("/game/<title>", rank = 1)]
async fn delete_game(
_token: auth::AdminToken,
_csrf: CsrfToken,
game_list: &rocket::State<Mutex<Vec<Game>>>,
user_list: &rocket::State<Mutex<Vec<User>>>,
title: &str,
@@ -227,7 +223,6 @@ async fn delete_game(
#[post("/refresh", rank = 1)]
async fn refresh_state(
_token: auth::AdminToken,
_csrf: CsrfToken,
game_list: &rocket::State<Mutex<Vec<Game>>>,
user_list: &rocket::State<Mutex<Vec<User>>>,
admin_state: &rocket::State<AdminState>,
@@ -256,7 +251,6 @@ async fn refresh_state(
#[post("/opinion", data = "<req>", rank = 1)]
async fn add_opinion(
token: auth::Token,
_csrf: CsrfToken,
game_list: &rocket::State<Mutex<Vec<Game>>>,
user_list: &rocket::State<Mutex<Vec<User>>>,
req: proto_utils::Proto<items::AddOpinionRequest>,
@@ -309,7 +303,6 @@ async fn add_opinion(
#[patch("/opinion", data = "<req>", rank = 1)]
async fn remove_opinion(
token: auth::Token,
_csrf: CsrfToken,
game_list: &rocket::State<Mutex<Vec<Game>>>,
user_list: &rocket::State<Mutex<Vec<User>>>,
req: proto_utils::Proto<items::RemoveOpinionRequest>,
@@ -495,7 +488,6 @@ async fn main() -> Result<(), std::io::Error> {
rocket::build()
.attach(SecurityHeaders)
.attach(CsrfFairing)
.manage(Mutex::new(user_list))
.manage(auth::AuthState::new())
.manage(auth::AdminState::new())
+1 -1
View File
@@ -23,7 +23,7 @@ impl Fairing for SecurityHeaders {
));
response.set_header(Header::new(
"Content-Security-Policy",
"default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self'; font-src 'self' data:; connect-src 'self'; frame-ancestors 'none';",
"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",
+7 -7
View File
@@ -13,7 +13,7 @@ importers:
dependencies:
'@bufbuild/protobuf':
specifier: ^2.10.2
version: 2.10.2
version: 2.13.0
react:
specifier: ^19.2.3
version: 19.2.3
@@ -149,8 +149,8 @@ packages:
resolution: {integrity: sha512-0ZrskXVEHSWIqZM/sQZ4EV3jZJXRkio/WCxaqKZP1g//CEWEPSfeZFcms4XeKBCHU0ZKnIkdJeU/kF+eRp5lBg==}
engines: {node: '>=6.9.0'}
'@bufbuild/protobuf@2.10.2':
resolution: {integrity: sha512-uFsRXwIGyu+r6AMdz+XijIIZJYpoWeYzILt5yZ2d3mCjQrWUTVpVD9WL/jZAbvp+Ed04rOhrsk7FiTcEDseB5A==}
'@bufbuild/protobuf@2.13.0':
resolution: {integrity: sha512-acq7c49vxfm1ggJ95P70TX7ABDM0vxr1SYD3BB0o0jnBLB4OAqeHyKuN+cD3w80gXEDQ2zxHpR6CUeA+O/aU9g==}
'@emnapi/core@1.8.1':
resolution: {integrity: sha512-AvT9QFpxK0Zd8J0jopedNm+w/2fIzvtPKPjqyw9jwvBaReTTqPBk9Hixaz7KbjimP+QNz605/XnjFcDAL2pqBg==}
@@ -425,7 +425,7 @@ packages:
resolution: {integrity: sha512-EcA07pHJouywpzsoTUqNh5NwGayl2PPVEJKUSinGGSxFGYn+shYbqMGBg6FXDqgXum9Ou/ecb+411ssw8HImJQ==}
engines: {node: ^20.19.0 || >=22.12.0}
peerDependencies:
vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0
vite: npm:rolldown-vite@7.2.5
acorn-jsx@5.3.2:
resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==}
@@ -1164,7 +1164,7 @@ snapshots:
'@babel/helper-string-parser': 7.27.1
'@babel/helper-validator-identifier': 7.28.5
'@bufbuild/protobuf@2.10.2': {}
'@bufbuild/protobuf@2.13.0': {}
'@emnapi/core@1.8.1':
dependencies:
@@ -1934,11 +1934,11 @@ snapshots:
ts-proto-descriptors@2.1.0:
dependencies:
'@bufbuild/protobuf': 2.10.2
'@bufbuild/protobuf': 2.13.0
ts-proto@2.10.1:
dependencies:
'@bufbuild/protobuf': 2.10.2
'@bufbuild/protobuf': 2.13.0
case-anything: 2.1.13
ts-poet: 6.12.0
ts-proto-descriptors: 2.1.0
-10
View File
@@ -1,26 +1,16 @@
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 (
url: string,
options: RequestInit = {}
): Promise<Response> => {
const token = localStorage.getItem("token");
const csrfToken = getCsrfToken();
const headers = new Headers(options.headers);
if (token) {
headers.set("Authorization", `Bearer ${token}`);
}
if (csrfToken) {
headers.set("X-CSRF-Token", csrfToken);
}
const config = {
...options,
headers,
@@ -35,7 +35,11 @@ export function FilteredGamesList({
const positiveCount = gameToPositive.get(game)?.size || 0;
const neutralCount = selectedPeopleCount - positiveCount;
const gameData = games.get(game);
const price = gameData?.price || 0;
if (!gameData) {
console.error("no data", game);
return null;
}
const price = gameData.price;
return (
<Link
@@ -81,7 +85,10 @@ export function FilteredGamesList({
padding: "0.2rem 0.6rem",
borderRadius: "4px",
display: "inline-block",
backgroundColor: price === 0 ? "rgba(76, 175, 80, 0.2)" : "rgba(255, 152, 0, 0.2)",
backgroundColor:
price === 0
? "rgba(76, 175, 80, 0.2)"
: "rgba(255, 152, 0, 0.2)",
color: price === 0 ? "#4caf50" : "#ff9800",
fontWeight: 600,
}}
+1 -3
View File
@@ -112,9 +112,7 @@ export function useGameFilter(
selectedPeople,
]);
const gamesMap = useMemo(() => {
return new Map(Object.entries(metaDataRef.current));
}, []);
const gamesMap = new Map(Object.entries(metaDataRef.current));
return { filteredGames, gameToPositive: gameToPositiveOpinion, games: gamesMap };
}