fix: resolve all remaining audit failures across rust, svelte, and java
This commit is contained in:
1 parent
bc12a25a01
commit
590178e41a
35 files changed
+958
-300
No files matched your search
@@ -264,9 +264,11 @@ pub async fn admin_update_achievement(
|
||||
State(state): State<AppState>,
|
||||
Json(payload): Json<AchievementPayload>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
let req_type = payload.requirement_type.unwrap_or_else(|| "stat".into());
|
||||
let req_key = payload.requirement_key.unwrap_or_else(|| "blocks_broken".into());
|
||||
let req_val = payload.requirement_value.unwrap_or(50);
|
||||
// FIX #19: Only overwrite requirement_type / key / value when the caller
|
||||
// explicitly supplies them. Use COALESCE so NULL leaves the existing value.
|
||||
let req_type = payload.requirement_type; // None if not in the request
|
||||
let req_key = payload.requirement_key; // None if not in the request
|
||||
let req_val = payload.requirement_value; // None if not in the request
|
||||
|
||||
sqlx::query(
|
||||
"UPDATE achievements SET
|
||||
@@ -277,9 +279,9 @@ pub async fn admin_update_achievement(
|
||||
icon_item = ?,
|
||||
icon_bg = ?,
|
||||
icon_border = ?,
|
||||
requirement_type = ?,
|
||||
requirement_key = ?,
|
||||
requirement_value = ?,
|
||||
requirement_type = COALESCE(?, requirement_type),
|
||||
requirement_key = COALESCE(?, requirement_key),
|
||||
requirement_value = COALESCE(?, requirement_value),
|
||||
xp_reward = ?,
|
||||
secret = COALESCE(?, secret)
|
||||
WHERE id = ?",
|
||||
|
||||
@@ -10,6 +10,62 @@ use scopenet_shared::{BaltopEntry, EconomyTransaction, MarketListing, ServerEcon
|
||||
use serde::Deserialize;
|
||||
use serde_json::Value;
|
||||
|
||||
async fn begin_operation(state: &AppState, server_id: i64, operation_id: &str) -> AppResult<(sqlx::Transaction<'static, sqlx::Sqlite>, Option<Value>)> {
|
||||
if operation_id.is_empty() || operation_id.len() > 100 { return Err(AppError::bad_request("Invalid operation ID")); }
|
||||
let mut tx = state.db.begin().await?;
|
||||
// The first statement obtains the write lock before reading any balances.
|
||||
let inserted = sqlx::query("INSERT OR IGNORE INTO economy_operations(server_id, operation_id, response) VALUES (?, ?, '')")
|
||||
.bind(server_id).bind(operation_id).execute(&mut *tx).await?.rows_affected();
|
||||
let previous = if inserted == 0 {
|
||||
let raw: String = sqlx::query_scalar("SELECT response FROM economy_operations WHERE server_id = ? AND operation_id = ?")
|
||||
.bind(server_id).bind(operation_id).fetch_one(&mut *tx).await?;
|
||||
Some(serde_json::from_str(&raw)?)
|
||||
} else { None };
|
||||
Ok((tx, previous))
|
||||
}
|
||||
|
||||
async fn finish_operation(mut tx: sqlx::Transaction<'_, sqlx::Sqlite>, server_id: i64, operation_id: &str, response: Value) -> AppResult<Json<Value>> {
|
||||
sqlx::query("UPDATE economy_operations SET response = ? WHERE server_id = ? AND operation_id = ?")
|
||||
.bind(response.to_string()).bind(server_id).bind(operation_id).execute(&mut *tx).await?;
|
||||
tx.commit().await?;
|
||||
Ok(Json(response))
|
||||
}
|
||||
|
||||
async fn ensure_balance(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, server_id: i64, uuid: &str, name: &str) -> AppResult<()> {
|
||||
sqlx::query("INSERT INTO server_economy(server_id, uuid, username, balance, updated_at) VALUES (?, ?, ?, 1000, ?) ON CONFLICT(server_id, uuid) DO NOTHING")
|
||||
.bind(server_id).bind(uuid).bind(name).bind(chrono::Utc::now().to_rfc3339()).execute(&mut **tx).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct AdjustBalancePayload {
|
||||
pub uuid: String,
|
||||
pub username: String,
|
||||
pub delta: f64,
|
||||
pub operation_id: String,
|
||||
pub description: String,
|
||||
}
|
||||
|
||||
pub async fn server_adjust_balance(GameServer(server): GameServer, State(state): State<AppState>, Json(p): Json<AdjustBalancePayload>) -> AppResult<Json<Value>> {
|
||||
if !p.delta.is_finite() || p.delta == 0.0 || p.delta.abs() > 1e12 { return Err(AppError::bad_request("Invalid amount")); }
|
||||
let (mut tx, previous) = begin_operation(&state, server.id, &p.operation_id).await?;
|
||||
if let Some(previous) = previous { return Ok(Json(previous)); }
|
||||
ensure_balance(&mut tx, server.id, &p.uuid, &p.username).await?;
|
||||
let balance: Option<f64> = sqlx::query_scalar("UPDATE server_economy SET balance = balance + ?, updated_at = ? WHERE server_id = ? AND uuid = ? AND balance + ? >= 0 RETURNING balance")
|
||||
.bind(p.delta).bind(chrono::Utc::now().to_rfc3339()).bind(server.id).bind(&p.uuid).bind(p.delta).fetch_optional(&mut *tx).await?;
|
||||
let Some(balance) = balance else { return Err(AppError::bad_request("Insufficient funds")); };
|
||||
let (from, from_name, to, to_name) = if p.delta > 0.0 { ("server", "Server Shop", p.uuid.as_str(), p.username.as_str()) } else { (p.uuid.as_str(), p.username.as_str(), "server", "Server Shop") };
|
||||
sqlx::query("INSERT INTO economy_transactions(server_id, from_uuid, from_name, to_uuid, to_name, amount, description, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)")
|
||||
.bind(server.id).bind(from).bind(from_name).bind(to).bind(to_name).bind(p.delta.abs()).bind(&p.description).bind(chrono::Utc::now().to_rfc3339()).execute(&mut *tx).await?;
|
||||
finish_operation(tx, server.id, &p.operation_id, serde_json::json!({"ok": true, "balance": balance})).await
|
||||
}
|
||||
|
||||
pub async fn server_market_read(GameServer(server): GameServer, State(state): State<AppState>) -> AppResult<Json<Vec<Value>>> {
|
||||
let rows: Vec<(i64, String, String, String, i32, f64, Option<String>)> = sqlx::query_as("SELECT id, seller_name, item_id, item_name, amount, price, item_data FROM server_market WHERE server_id = ? ORDER BY id DESC LIMIT 45")
|
||||
.bind(server.id).fetch_all(&state.db).await?;
|
||||
Ok(Json(rows.into_iter().map(|(id, seller, item_id, item_name, amount, price, data)| serde_json::json!({"id":id,"seller_name":seller,"item_id":item_id,"item_name":item_name,"amount":amount,"price":price,"item_data":data})).collect()))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Launcher & Public Economy API
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -213,7 +269,7 @@ pub async fn server_transfer(
|
||||
State(state): State<AppState>,
|
||||
Json(payload): Json<ServerTransferPayload>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
if payload.amount <= 0.0 {
|
||||
if !payload.amount.is_finite() || payload.amount <= 0.0 {
|
||||
return Err(AppError::bad_request("Transfer amount must be positive"));
|
||||
}
|
||||
|
||||
@@ -347,6 +403,8 @@ pub async fn server_baltop(
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct MarketListPayload {
|
||||
pub operation_id: String,
|
||||
pub item_data: Option<String>,
|
||||
pub seller_uuid: String,
|
||||
pub seller_name: String,
|
||||
pub item_id: String,
|
||||
@@ -360,10 +418,13 @@ pub async fn server_market_list(
|
||||
State(state): State<AppState>,
|
||||
Json(payload): Json<MarketListPayload>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
if !payload.price.is_finite() || payload.price <= 0.0 || payload.amount <= 0 || payload.amount > 64 { return Err(AppError::bad_request("Invalid listing")); }
|
||||
let (mut tx, previous) = begin_operation(&state, server.id, &payload.operation_id).await?;
|
||||
if let Some(previous) = previous { return Ok(Json(previous)); }
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
let id: i64 = sqlx::query_scalar(
|
||||
"INSERT INTO server_market (server_id, seller_uuid, seller_name, item_id, item_name, amount, price, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
"INSERT INTO server_market (server_id, seller_uuid, seller_name, item_id, item_name, amount, price, created_at, item_data)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
RETURNING id",
|
||||
)
|
||||
.bind(server.id)
|
||||
@@ -374,14 +435,16 @@ pub async fn server_market_list(
|
||||
.bind(payload.amount)
|
||||
.bind(payload.price)
|
||||
.bind(&now)
|
||||
.fetch_one(&state.db)
|
||||
.bind(&payload.item_data)
|
||||
.fetch_one(&mut *tx)
|
||||
.await?;
|
||||
|
||||
Ok(Json(serde_json::json!({ "id": id, "ok": true })))
|
||||
finish_operation(tx, server.id, &payload.operation_id, serde_json::json!({ "id": id, "ok": true })).await
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct MarketBuyPayload {
|
||||
pub operation_id: String,
|
||||
pub listing_id: i64,
|
||||
pub buyer_uuid: String,
|
||||
pub buyer_name: String,
|
||||
@@ -392,21 +455,24 @@ pub async fn server_market_buy(
|
||||
State(state): State<AppState>,
|
||||
Json(payload): Json<MarketBuyPayload>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
let listing: Option<(String, String, String, String, i32, f64)> = sqlx::query_as(
|
||||
"SELECT seller_uuid, seller_name, item_id, item_name, amount, price
|
||||
FROM server_market
|
||||
WHERE id = ? AND server_id = ?",
|
||||
let (mut tx, previous) = begin_operation(&state, server.id, &payload.operation_id).await?;
|
||||
if let Some(previous) = previous { return Ok(Json(previous)); }
|
||||
let listing: Option<(String, String, String, String, i32, f64, Option<String>)> = sqlx::query_as(
|
||||
"DELETE FROM server_market
|
||||
WHERE id = ? AND server_id = ?
|
||||
RETURNING seller_uuid, seller_name, item_id, item_name, amount, price, item_data
|
||||
",
|
||||
)
|
||||
.bind(payload.listing_id)
|
||||
.bind(server.id)
|
||||
.fetch_optional(&state.db)
|
||||
.fetch_optional(&mut *tx)
|
||||
.await?;
|
||||
|
||||
let Some((seller_uuid, seller_name, item_id, item_name, amount, price)) = listing else {
|
||||
let Some((seller_uuid, seller_name, item_id, item_name, amount, price, item_data)) = listing else {
|
||||
return Err(AppError::not_found("Listing not found"));
|
||||
};
|
||||
|
||||
let mut tx = state.db.begin().await?;
|
||||
ensure_balance(&mut tx, server.id, &payload.buyer_uuid, &payload.buyer_name).await?;
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
|
||||
// Deduct buyer
|
||||
@@ -471,13 +537,12 @@ pub async fn server_market_buy(
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(Json(serde_json::json!({
|
||||
finish_operation(tx, server.id, &payload.operation_id, serde_json::json!({
|
||||
"ok": true,
|
||||
"item_id": item_id,
|
||||
"item_data": item_data,
|
||||
"item_name": item_name,
|
||||
"amount": amount,
|
||||
"price": price
|
||||
})))
|
||||
})).await
|
||||
}
|
||||
@@ -220,7 +220,7 @@ async fn fetch_guild_detail(state: &AppState, guild_id: &str) -> AppResult<Guild
|
||||
|
||||
// Claims
|
||||
let claim_rows: Vec<(i64, String, i64, String, i32, i32, String, String)> = sqlx::query_as(
|
||||
"SELECT id, guild_id, server_id, dimension, chunk_x, chunk_z, claimed_by_uuid, claimed_at
|
||||
"SELECT id, guild_id, COALESCE(server_id, 0), dimension, chunk_x, chunk_z, claimed_by_uuid, claimed_at
|
||||
FROM guild_claims
|
||||
WHERE guild_id = ?
|
||||
LIMIT 200",
|
||||
@@ -279,6 +279,14 @@ pub async fn get_guild_by_id(
|
||||
fetch_guild_detail(&state, &id).await.map(Json)
|
||||
}
|
||||
|
||||
pub async fn get_guild_members(Path(id): Path<String>, State(state): State<AppState>) -> AppResult<Json<Vec<GuildMember>>> {
|
||||
Ok(Json(fetch_guild_detail(&state, &id).await?.members))
|
||||
}
|
||||
|
||||
pub async fn get_guild_posts(Path(id): Path<String>, State(state): State<AppState>) -> AppResult<Json<Vec<GuildPost>>> {
|
||||
Ok(Json(fetch_guild_detail(&state, &id).await?.posts))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct CreateGuildPayload {
|
||||
pub instance_id: String,
|
||||
@@ -366,6 +374,7 @@ pub async fn create_guild(
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
crate::routes::leveling::grant_rewards(&mut tx, &auth.uuid, &now).await?;
|
||||
tx.commit().await?;
|
||||
|
||||
fetch_guild_detail(&state, &guild_id).await.map(Json)
|
||||
@@ -549,13 +558,14 @@ pub async fn create_guild_post(
|
||||
.bind(&id)
|
||||
.bind(&auth.uuid)
|
||||
.bind(&auth.username)
|
||||
.bind(payload.title)
|
||||
.bind(payload.content)
|
||||
.bind(&payload.title)
|
||||
.bind(&payload.content)
|
||||
.bind(&now)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
|
||||
Ok(Json(serde_json::json!({ "id": post_id, "ok": true })))
|
||||
Ok(Json(serde_json::json!({ "id": post_id, "guild_id": id, "author_uuid": auth.uuid,
|
||||
"author_name": auth.username, "title": payload.title, "content": payload.content, "created_at": now })))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -604,29 +614,28 @@ pub async fn claim_chunk(
|
||||
return Err(AppError::bad_request(format!("Guild reached its max claim limit of {max_claims} chunks")));
|
||||
}
|
||||
|
||||
let server_id = payload.server_id.ok_or_else(|| AppError::bad_request("Select a game server for this claim"))?;
|
||||
let matches: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM game_servers s JOIN guilds g ON g.instance_id = s.instance_id WHERE s.id = ? AND g.id = ?)")
|
||||
.bind(server_id).bind(&guild_id).fetch_one(&state.db).await?;
|
||||
if !matches { return Err(AppError::bad_request("Server is not linked to this guild's instance")); }
|
||||
let dim = payload.dimension.unwrap_or_else(|| "minecraft:overworld".into());
|
||||
let now = chrono::Utc::now().to_rfc3339();
|
||||
|
||||
let res = sqlx::query(
|
||||
let res = sqlx::query_scalar::<_, i64>(
|
||||
"INSERT INTO guild_claims (guild_id, server_id, dimension, chunk_x, chunk_z, claimed_by_uuid, claimed_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)",
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING id",
|
||||
)
|
||||
.bind(&guild_id)
|
||||
.bind(payload.server_id)
|
||||
.bind(server_id)
|
||||
.bind(&dim)
|
||||
.bind(payload.chunk_x)
|
||||
.bind(payload.chunk_z)
|
||||
.bind(&auth.uuid)
|
||||
.bind(&now)
|
||||
.execute(&state.db)
|
||||
.fetch_one(&state.db)
|
||||
.await;
|
||||
|
||||
if let Err(e) = res {
|
||||
tracing::warn!("claim chunk failed: {e}");
|
||||
return Err(AppError::bad_request("Chunk is already claimed by another guild"));
|
||||
}
|
||||
|
||||
let claim_id: i64 = sqlx::query_scalar("SELECT last_insert_rowid()").fetch_one(&state.db).await.unwrap_or(1);
|
||||
let claim_id = res.map_err(|_| AppError::bad_request("Chunk is already claimed"))?;
|
||||
|
||||
// Award achievement for claiming land
|
||||
sqlx::query(
|
||||
@@ -638,7 +647,8 @@ pub async fn claim_chunk(
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
|
||||
Ok(Json(serde_json::json!({ "ok": true, "id": claim_id, "chunk_x": payload.chunk_x, "chunk_z": payload.chunk_z })))
|
||||
let detail = fetch_guild_detail(&state, &guild_id).await?;
|
||||
Ok(Json(serde_json::to_value(detail.claims.into_iter().find(|c| c.id == claim_id).ok_or_else(|| AppError::not_found("Claim not found"))?)?))
|
||||
}
|
||||
|
||||
/// Unclaim a chunk by coordinates.
|
||||
@@ -951,9 +961,10 @@ pub async fn server_claim_chunk(
|
||||
Json(payload): Json<ServerClaimChunkPayload>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
let member: Option<(String, String)> = sqlx::query_as(
|
||||
"SELECT guild_id, role FROM guild_members WHERE uuid = ?",
|
||||
"SELECT gm.guild_id, gm.role FROM guild_members gm JOIN guilds g ON g.id = gm.guild_id WHERE gm.uuid = ? AND g.instance_id = ?",
|
||||
)
|
||||
.bind(&payload.uuid)
|
||||
.bind(&server.instance_id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
|
||||
@@ -1036,6 +1047,7 @@ pub async fn server_unclaim_chunk(
|
||||
)
|
||||
.bind(&guild_id)
|
||||
.bind(&payload.uuid)
|
||||
.bind(&server.instance_id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
|
||||
@@ -1057,14 +1069,15 @@ pub struct ServerGuildPlayerQuery {
|
||||
}
|
||||
|
||||
pub async fn server_get_player_guild(
|
||||
GameServer(_server): GameServer,
|
||||
GameServer(server): GameServer,
|
||||
State(state): State<AppState>,
|
||||
Json(payload): Json<ServerGuildPlayerQuery>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
let member_opt: Option<(String, String)> = sqlx::query_as(
|
||||
"SELECT guild_id, role FROM guild_members WHERE uuid = ?",
|
||||
"SELECT gm.guild_id, gm.role FROM guild_members gm JOIN guilds g ON g.id = gm.guild_id WHERE gm.uuid = ? AND g.instance_id = ?",
|
||||
)
|
||||
.bind(&payload.uuid)
|
||||
.bind(&server.instance_id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
|
||||
@@ -1129,7 +1142,7 @@ pub struct ServerCreateGuildPayload {
|
||||
}
|
||||
|
||||
pub async fn server_create_guild(
|
||||
GameServer(_server): GameServer,
|
||||
GameServer(server): GameServer,
|
||||
State(state): State<AppState>,
|
||||
Json(payload): Json<ServerCreateGuildPayload>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
@@ -1142,8 +1155,9 @@ pub async fn server_create_guild(
|
||||
return Err(AppError::bad_request("Guild tag must be between 2 and 6 characters"));
|
||||
}
|
||||
|
||||
let in_guild: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM guild_members WHERE uuid = ?)")
|
||||
let in_guild: bool = sqlx::query_scalar("SELECT EXISTS(SELECT 1 FROM guild_members gm JOIN guilds g ON g.id = gm.guild_id WHERE gm.uuid = ? AND g.instance_id = ?)")
|
||||
.bind(&payload.uuid)
|
||||
.bind(&server.instance_id)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
|
||||
@@ -1158,9 +1172,10 @@ pub async fn server_create_guild(
|
||||
|
||||
let res = sqlx::query(
|
||||
"INSERT INTO guilds (id, instance_id, name, tag, description, motd, leader_uuid, created_at)
|
||||
VALUES (?, '', ?, ?, '', 'Welcome to the guild!', ?, ?)",
|
||||
VALUES (?, ?, ?, ?, '', 'Welcome to the guild!', ?, ?)",
|
||||
)
|
||||
.bind(&guild_id)
|
||||
.bind(&server.instance_id)
|
||||
.bind(name)
|
||||
.bind(tag)
|
||||
.bind(&payload.uuid)
|
||||
@@ -1200,14 +1215,15 @@ pub struct ServerGuildLeavePayload {
|
||||
}
|
||||
|
||||
pub async fn server_guild_leave(
|
||||
GameServer(_server): GameServer,
|
||||
GameServer(server): GameServer,
|
||||
State(state): State<AppState>,
|
||||
Json(payload): Json<ServerGuildLeavePayload>,
|
||||
) -> AppResult<Json<Value>> {
|
||||
let member_opt: Option<(String, String)> = sqlx::query_as(
|
||||
"SELECT guild_id, role FROM guild_members WHERE uuid = ?",
|
||||
"SELECT gm.guild_id, gm.role FROM guild_members gm JOIN guilds g ON g.id = gm.guild_id WHERE gm.uuid = ? AND g.instance_id = ?",
|
||||
)
|
||||
.bind(&payload.uuid)
|
||||
.bind(&server.instance_id)
|
||||
.fetch_optional(&state.db)
|
||||
.await?;
|
||||
|
||||
|
||||
@@ -34,6 +34,49 @@ pub fn level_from_xp(xp: i64) -> (i64, i64, i64, f64) {
|
||||
(lvl, progress_in_lvl, span, pct)
|
||||
}
|
||||
|
||||
/// Award each configured entitlement once in the transaction which earned it.
|
||||
/// Achievement XP is credited automatically via the `achievement_xp` DB trigger;
|
||||
/// this function only processes level-up rewards (titles, badges, item entitlements).
|
||||
pub async fn grant_rewards(tx: &mut sqlx::Transaction<'_, sqlx::Sqlite>, uuid: &str, now: &str) -> AppResult<()> {
|
||||
let xp: i64 = sqlx::query_scalar("SELECT global_xp FROM user_levels WHERE uuid = ?")
|
||||
.bind(uuid).fetch_optional(&mut **tx).await?.unwrap_or(0);
|
||||
let level = level_from_xp(xp).0;
|
||||
sqlx::query("UPDATE user_levels SET global_level = ? WHERE uuid = ?")
|
||||
.bind(level).bind(uuid).execute(&mut **tx).await?;
|
||||
let rewards: Vec<(i64, String, Option<i64>, String, String, String)> = sqlx::query_as(
|
||||
"SELECT r.id, r.level_type, r.server_id, r.reward_type, r.reward_name, r.reward_data FROM level_rewards r
|
||||
WHERE (r.level_type = 'global' AND r.level_req <= ?)
|
||||
OR (r.level_type = 'server' AND EXISTS (SELECT 1 FROM server_levels sl WHERE sl.uuid = ? AND sl.server_id = r.server_id AND sl.server_level >= r.level_req))
|
||||
ORDER BY r.level_req, r.id")
|
||||
.bind(level).bind(uuid).fetch_all(&mut **tx).await?;
|
||||
for (id, scope, server_id, kind, name, data) in rewards {
|
||||
let inserted = sqlx::query("INSERT OR IGNORE INTO granted_rewards(uuid, reward_id, granted_at) VALUES (?, ?, ?)")
|
||||
.bind(uuid).bind(id).bind(now).execute(&mut **tx).await?.rows_affected();
|
||||
if inserted == 0 { continue; }
|
||||
match kind.as_str() {
|
||||
"title" if scope == "global" => {
|
||||
sqlx::query("UPDATE user_levels SET title = ? WHERE uuid = ?").bind(&name).bind(uuid).execute(&mut **tx).await?;
|
||||
}
|
||||
"title" => {
|
||||
sqlx::query("UPDATE server_levels SET rank_name = ? WHERE server_id = ? AND uuid = ?")
|
||||
.bind(&name).bind(server_id).bind(uuid).execute(&mut **tx).await?;
|
||||
}
|
||||
"badge" | "profile_badge" => {
|
||||
let raw: String = sqlx::query_scalar("SELECT badges FROM user_levels WHERE uuid = ?")
|
||||
.bind(uuid).fetch_optional(&mut **tx).await?.unwrap_or_else(|| "[]".into());
|
||||
let mut badges: Vec<String> = serde_json::from_str(&raw).unwrap_or_default();
|
||||
let data: Value = serde_json::from_str(&data).unwrap_or_default();
|
||||
let badge = data["badge"].as_str().unwrap_or(&name).to_string();
|
||||
if !badges.contains(&badge) { badges.push(badge); }
|
||||
sqlx::query("INSERT INTO user_levels(uuid, badges, updated_at) VALUES (?, ?, ?) ON CONFLICT(uuid) DO UPDATE SET badges = excluded.badges")
|
||||
.bind(uuid).bind(serde_json::to_string(&badges)?).bind(now).execute(&mut **tx).await?;
|
||||
}
|
||||
_ => {} // Item/cosmetic entitlements are recorded in granted_rewards.
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
pub struct RewardRow {
|
||||
pub id: i64,
|
||||
|
||||
@@ -61,9 +61,9 @@ pub fn api(state: &AppState) -> Router<AppState> {
|
||||
.route("/guilds/claims/grid", get(guilds::get_chunk_grid))
|
||||
.route("/guilds/claims/{id}", delete(guilds::unclaim_by_id))
|
||||
.route("/guilds/{id}", get(guilds::get_guild_by_id).put(guilds::update_guild))
|
||||
.route("/guilds/{id}/members", post(guilds::add_guild_member))
|
||||
.route("/guilds/{id}/members", get(guilds::get_guild_members).post(guilds::add_guild_member))
|
||||
.route("/guilds/{id}/members/{uuid}", delete(guilds::remove_guild_member))
|
||||
.route("/guilds/{id}/posts", post(guilds::create_guild_post))
|
||||
.route("/guilds/{id}/posts", get(guilds::get_guild_posts).post(guilds::create_guild_post))
|
||||
.route("/guilds/{id}/claims", post(guilds::claim_chunk).delete(guilds::unclaim_chunk))
|
||||
.route("/guilds/{id}/claim", post(guilds::claim_chunk))
|
||||
.route("/guilds/{id}/unclaim", post(guilds::unclaim_chunk))
|
||||
@@ -161,6 +161,8 @@ pub fn api(state: &AppState) -> Router<AppState> {
|
||||
.route("/economy/balance", post(economy::server_get_balance))
|
||||
.route("/economy/pay", post(economy::server_transfer))
|
||||
.route("/economy/transfer", post(economy::server_transfer))
|
||||
.route("/economy/adjust", post(economy::server_adjust_balance))
|
||||
.route("/economy/market", post(economy::server_market_read))
|
||||
.route("/economy/sync-balance", post(economy::server_sync_balance))
|
||||
.route("/economy/baltop", post(economy::server_baltop))
|
||||
.route("/economy/market/list", post(economy::server_market_list))
|
||||
|
||||
@@ -205,6 +205,7 @@ pub async fn claim_quest(
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
crate::routes::leveling::grant_rewards(&mut tx, &auth.uuid, &now).await?;
|
||||
tx.commit().await?;
|
||||
|
||||
Ok(Json(serde_json::json!({
|
||||
|
||||
@@ -60,6 +60,7 @@ fn clip(s: &str, max: usize) -> String {
|
||||
|
||||
#[derive(Debug, Clone, sqlx::FromRow, Serialize)]
|
||||
pub struct ServerRow {
|
||||
pub instance_id: String,
|
||||
pub id: i64,
|
||||
pub name: String,
|
||||
#[serde(skip)]
|
||||
@@ -232,43 +233,9 @@ fn canonical_ip(ip: std::net::IpAddr) -> std::net::IpAddr {
|
||||
}
|
||||
}
|
||||
|
||||
fn is_private_or_local(ip: &std::net::IpAddr) -> bool {
|
||||
match canonical_ip(*ip) {
|
||||
std::net::IpAddr::V4(v4) => v4.is_loopback() || v4.is_private() || v4.is_link_local(),
|
||||
std::net::IpAddr::V6(v6) => v6.is_loopback(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn ips_match(sess_str: &str, req_str: &str) -> bool {
|
||||
let s = sess_str.trim();
|
||||
let r = req_str.trim();
|
||||
if s.eq_ignore_ascii_case(r) {
|
||||
return true;
|
||||
}
|
||||
let (Ok(ip_a), Ok(ip_b)) = (s.parse::<std::net::IpAddr>(), r.parse::<std::net::IpAddr>()) else {
|
||||
return false;
|
||||
};
|
||||
let a = canonical_ip(ip_a);
|
||||
let b = canonical_ip(ip_b);
|
||||
if a == b {
|
||||
return true;
|
||||
}
|
||||
if a.is_loopback() && b.is_loopback() {
|
||||
return true;
|
||||
}
|
||||
if is_private_or_local(&a) && is_private_or_local(&b) {
|
||||
return true;
|
||||
}
|
||||
if is_private_or_local(&a) {
|
||||
return true;
|
||||
}
|
||||
match (a, b) {
|
||||
(std::net::IpAddr::V4(v4_a), std::net::IpAddr::V4(v4_b)) => {
|
||||
v4_a.octets()[0..3] == v4_b.octets()[0..3]
|
||||
}
|
||||
(std::net::IpAddr::V6(v6_a), std::net::IpAddr::V6(v6_b)) => {
|
||||
v6_a.segments()[0..4] == v6_b.segments()[0..4]
|
||||
}
|
||||
match (sess_str.trim().parse::<std::net::IpAddr>(), req_str.trim().parse::<std::net::IpAddr>()) {
|
||||
(Ok(a), Ok(b)) => canonical_ip(a) == canonical_ip(b),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
@@ -553,6 +520,10 @@ pub async fn sync(GameServer(server): GameServer, State(state): State<AppState>,
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut rewarded = std::collections::HashSet::new();
|
||||
for d in &s.stats { if let Some(uuid) = dashed(&d.uuid) { rewarded.insert(uuid); } }
|
||||
for e in &s.events { if let Some(uuid) = e.uuid.as_deref().and_then(dashed) { rewarded.insert(uuid); } }
|
||||
for uuid in rewarded { crate::routes::leveling::grant_rewards(&mut tx, &uuid, &at_now).await?; }
|
||||
tx.commit().await?;
|
||||
|
||||
// Occasional housekeeping.
|
||||
@@ -786,7 +757,7 @@ async fn update_progression_for_delta(
|
||||
.fetch_optional(&mut **tx)
|
||||
.await?;
|
||||
|
||||
if let Some(lvl) = global_level {
|
||||
if let Some(lvl) = global_level.filter(|_| achievements_on) {
|
||||
let lvl_ach: Vec<String> = sqlx::query_scalar(
|
||||
"SELECT id FROM achievements WHERE requirement_type = 'level' AND requirement_value <= ?",
|
||||
)
|
||||
@@ -820,6 +791,8 @@ pub async fn list(_: AdminUser, State(state): State<AppState>) -> AppResult<Json
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct ServerInput {
|
||||
#[serde(default)]
|
||||
instance_id: String,
|
||||
name: String,
|
||||
#[serde(default = "default_access")]
|
||||
access: String,
|
||||
@@ -860,7 +833,7 @@ pub async fn create(_: AdminUser, State(state): State<AppState>, Json(input): Js
|
||||
input.validate()?;
|
||||
let token = new_token();
|
||||
let id: i64 = sqlx::query_scalar(
|
||||
"INSERT INTO game_servers (name, token_hash, token_hint, access, allowed_groups, require_launcher, created_at) VALUES (?, ?, ?, ?, ?, ?, ?) RETURNING id",
|
||||
"INSERT INTO game_servers (name, token_hash, token_hint, access, allowed_groups, require_launcher, created_at, instance_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
|
||||
)
|
||||
.bind(input.name.trim())
|
||||
.bind(hash_token(&token))
|
||||
@@ -869,6 +842,7 @@ pub async fn create(_: AdminUser, State(state): State<AppState>, Json(input): Js
|
||||
.bind(serde_json::to_string(&input.allowed_groups).unwrap_or_else(|_| "[]".into()))
|
||||
.bind(input.require_launcher)
|
||||
.bind(now())
|
||||
.bind(&input.instance_id)
|
||||
.fetch_one(&state.db)
|
||||
.await?;
|
||||
let server = get_server(&state, id).await?;
|
||||
@@ -883,11 +857,12 @@ pub async fn update(
|
||||
) -> AppResult<Json<ServerView>> {
|
||||
input.validate()?;
|
||||
get_server(&state, id).await?;
|
||||
sqlx::query("UPDATE game_servers SET name = ?, access = ?, allowed_groups = ?, require_launcher = ? WHERE id = ?")
|
||||
sqlx::query("UPDATE game_servers SET name = ?, access = ?, allowed_groups = ?, require_launcher = ?, instance_id = ? WHERE id = ?")
|
||||
.bind(input.name.trim())
|
||||
.bind(&input.access)
|
||||
.bind(serde_json::to_string(&input.allowed_groups).unwrap_or_else(|_| "[]".into()))
|
||||
.bind(input.require_launcher)
|
||||
.bind(&input.instance_id)
|
||||
.bind(id)
|
||||
.execute(&state.db)
|
||||
.await?;
|
||||
@@ -1070,6 +1045,7 @@ pub async fn public_servers(State(state): State<AppState>) -> AppResult<Json<Val
|
||||
json!({
|
||||
"id": s.id,
|
||||
"name": s.name,
|
||||
"instance_id": s.instance_id,
|
||||
"online": is_online,
|
||||
"players_online": if is_online { s.online_count } else { 0 },
|
||||
"players_max": s.max_players,
|
||||
@@ -1225,8 +1201,8 @@ mod tests {
|
||||
assert!(ips_match("203.0.113.9", "203.0.113.9"));
|
||||
|
||||
// Loopback IPv4 & IPv6
|
||||
assert!(ips_match("127.0.0.1", "::1"));
|
||||
assert!(ips_match("::1", "127.0.0.1"));
|
||||
assert!(!ips_match("127.0.0.1", "::1"));
|
||||
assert!(!ips_match("::1", "127.0.0.1"));
|
||||
assert!(ips_match("127.0.0.1", "127.0.0.1"));
|
||||
|
||||
// IPv4-mapped IPv6
|
||||
@@ -1234,11 +1210,11 @@ mod tests {
|
||||
assert!(ips_match("192.168.1.10", "::ffff:192.168.1.10"));
|
||||
|
||||
// Docker bridge / private gateway recorded
|
||||
assert!(ips_match("172.18.0.1", "192.168.1.50"));
|
||||
assert!(ips_match("10.0.0.1", "10.0.0.2"));
|
||||
assert!(!ips_match("172.18.0.1", "192.168.1.50"));
|
||||
assert!(!ips_match("10.0.0.1", "10.0.0.2"));
|
||||
|
||||
// Subnet /24 match
|
||||
assert!(ips_match("203.0.113.5", "203.0.113.9"));
|
||||
assert!(!ips_match("203.0.113.5", "203.0.113.9"));
|
||||
|
||||
// Different public networks do not match
|
||||
assert!(!ips_match("198.51.100.1", "203.0.113.9"));
|
||||
|
||||
@@ -218,23 +218,49 @@ pub async fn respond_friend_request(
|
||||
// Direct Messaging (DMs)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
pub struct DmQuery {
|
||||
pub before_id: Option<i64>,
|
||||
}
|
||||
|
||||
pub async fn get_direct_messages(
|
||||
auth: AuthUser,
|
||||
Path(target_uuid): Path<String>,
|
||||
Query(q): Query<DmQuery>,
|
||||
State(state): State<AppState>,
|
||||
) -> AppResult<Json<Vec<DirectMessage>>> {
|
||||
let rows: Vec<(i64, String, String, String, String, bool, String)> = sqlx::query_as(
|
||||
"SELECT id, sender_uuid, sender_name, recipient_uuid, content, is_read, created_at
|
||||
FROM direct_messages
|
||||
WHERE (sender_uuid = ? AND recipient_uuid = ?) OR (sender_uuid = ? AND recipient_uuid = ?)
|
||||
ORDER BY id ASC LIMIT 100",
|
||||
)
|
||||
.bind(&auth.uuid)
|
||||
.bind(&target_uuid)
|
||||
.bind(&target_uuid)
|
||||
.bind(&auth.uuid)
|
||||
.fetch_all(&state.db)
|
||||
.await?;
|
||||
// FIX #13: Support optional before_id cursor for pagination beyond the first 100 messages.
|
||||
let mut rows: Vec<(i64, String, String, String, String, bool, String)> = if let Some(before) = q.before_id {
|
||||
sqlx::query_as(
|
||||
"SELECT id, sender_uuid, sender_name, recipient_uuid, content, is_read, created_at
|
||||
FROM direct_messages
|
||||
WHERE ((sender_uuid = ? AND recipient_uuid = ?) OR (sender_uuid = ? AND recipient_uuid = ?))
|
||||
AND id < ?
|
||||
ORDER BY id DESC LIMIT 100",
|
||||
)
|
||||
.bind(&auth.uuid)
|
||||
.bind(&target_uuid)
|
||||
.bind(&target_uuid)
|
||||
.bind(&auth.uuid)
|
||||
.bind(before)
|
||||
.fetch_all(&state.db)
|
||||
.await?
|
||||
} else {
|
||||
sqlx::query_as(
|
||||
"SELECT id, sender_uuid, sender_name, recipient_uuid, content, is_read, created_at
|
||||
FROM direct_messages
|
||||
WHERE (sender_uuid = ? AND recipient_uuid = ?) OR (sender_uuid = ? AND recipient_uuid = ?)
|
||||
ORDER BY id DESC LIMIT 100",
|
||||
)
|
||||
.bind(&auth.uuid)
|
||||
.bind(&target_uuid)
|
||||
.bind(&target_uuid)
|
||||
.bind(&auth.uuid)
|
||||
.fetch_all(&state.db)
|
||||
.await?
|
||||
};
|
||||
|
||||
rows.reverse();
|
||||
|
||||
// Mark unread messages sent to me as read
|
||||
sqlx::query(
|
||||
@@ -492,7 +518,24 @@ pub async fn get_player_profile(
|
||||
})
|
||||
.collect();
|
||||
|
||||
let achievements = crate::routes::achievements::get_achievements_for_user(&state, &puuid, true).await?;
|
||||
let friends_count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM friendships WHERE status = 'accepted' AND (user_uuid = ? OR friend_uuid = ?)")
|
||||
.bind(&puuid).bind(&puuid).fetch_one(&state.db).await?;
|
||||
let created_at: String = sqlx::query_scalar("SELECT created_at FROM users WHERE uuid = ?")
|
||||
.bind(&puuid).fetch_one(&state.db).await?;
|
||||
let stats: Option<crate::routes::servers::AggregatedStatRow> = sqlx::query_as(
|
||||
"SELECT uuid, name, SUM(playtime_secs) playtime_secs, SUM(joins) joins, SUM(deaths) deaths,
|
||||
SUM(player_kills) player_kills, SUM(mob_kills) mob_kills, SUM(blocks_broken) blocks_broken,
|
||||
SUM(blocks_placed) blocks_placed, SUM(messages) messages, MIN(first_seen) first_seen, MAX(last_seen) last_seen
|
||||
FROM player_stats WHERE uuid = ? GROUP BY uuid")
|
||||
.bind(&puuid).fetch_optional(&state.db).await?;
|
||||
Ok(Json(UserProfileView {
|
||||
level_info: levels.clone(),
|
||||
badges: levels.badges.clone(),
|
||||
achievements,
|
||||
friends_count,
|
||||
created_at,
|
||||
stats: stats.map(|s| serde_json::to_value(s).unwrap()),
|
||||
uuid: puuid,
|
||||
username,
|
||||
bio,
|
||||
|
||||
Reference in new issue
Block a user